config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

org-indent.el (17694B)


      1 ;;; org-indent.el --- Dynamic indentation for Org    -*- lexical-binding: t; -*-
      2 
      3 ;; Copyright (C) 2009-2024 Free Software Foundation, Inc.
      4 ;;
      5 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
      6 ;; Keywords: outlines, hypermedia, calendar, text
      7 ;; URL: https://orgmode.org
      8 ;;
      9 ;; This file is part of GNU Emacs.
     10 ;;
     11 ;; GNU Emacs is free software: you can redistribute it and/or modify
     12 ;; it under the terms of the GNU General Public License as published by
     13 ;; the Free Software Foundation, either version 3 of the License, or
     14 ;; (at your option) any later version.
     15 ;;
     16 ;; GNU Emacs is distributed in the hope that it will be useful,
     17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     19 ;; GNU General Public License for more details.
     20 ;;
     21 ;; You should have received a copy of the GNU General Public License
     22 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     23 ;;
     24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
     25 ;;
     26 ;;; Commentary:
     27 
     28 ;; This is an implementation of dynamic virtual indentation.  It works
     29 ;; by adding text properties to a buffer to make sure lines are
     30 ;; indented according to outline structure.
     31 ;;
     32 ;; The process is synchronous, toggled at every buffer modification.
     33 ;; Though, the initialization (indentation of text already in the
     34 ;; buffer), which can take a few seconds in large buffers, happens on
     35 ;; idle time.
     36 ;;
     37 ;;; Code:
     38 
     39 (require 'org-macs)
     40 (org-assert-version)
     41 
     42 (require 'org-macs)
     43 (require 'org-compat)
     44 (require 'org)
     45 
     46 (require 'cl-lib)
     47 
     48 (declare-function org-inlinetask-get-task-level "org-inlinetask" ())
     49 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
     50 (declare-function org-list-item-body-column "org-list" (item))
     51 (defvar org-inlinetask-show-first-star)
     52 
     53 (defgroup org-indent nil
     54   "Options concerning dynamic virtual outline indentation."
     55   :tag "Org Indent"
     56   :group 'org)
     57 
     58 (defvar org-indent-inlinetask-first-star (org-add-props "*" '(face org-warning))
     59   "First star of inline tasks, with correct face.")
     60 (defvar org-indent-agent-timer nil
     61   "Timer running the initialize agent.")
     62 (defvar org-indent-agentized-buffers nil
     63   "List of buffers watched by the initialize agent.")
     64 (defvar org-indent-agent-resume-timer nil
     65   "Timer to reschedule agent after switching to other idle processes.")
     66 (defvar org-indent-agent-active-delay '(0 2 0)
     67   "Time to run agent before switching to other idle processes.
     68 Delay used when the buffer to initialize is current.")
     69 (defvar org-indent-agent-passive-delay '(0 0 400000)
     70   "Time to run agent before switching to other idle processes.
     71 Delay used when the buffer to initialize isn't current.")
     72 (defvar org-indent-agent-resume-delay '(0 0 100000)
     73   "Minimal time for other idle processes before switching back to agent.")
     74 (defvar org-indent--initial-marker nil
     75   "Position of initialization before interrupt.
     76 This is used locally in each buffer being initialized.")
     77 (defvar org-indent-modified-headline-flag nil
     78   "Non-nil means the last deletion operated on a headline.
     79 It is modified by `org-indent-notify-modified-headline'.")
     80 
     81 
     82 (defcustom org-indent-boundary-char ?\s
     83   "The end of the virtual indentation strings, a single-character string.
     84 The default is just a space, but if you wish, you can use \"|\" or so.
     85 This can be useful on a terminal window - under a windowing system,
     86 it may be prettier to customize the `org-indent' face."
     87   :group 'org-indent
     88   :type 'character)
     89 
     90 (defcustom org-indent-mode-turns-off-org-adapt-indentation t
     91   "Non-nil means setting `org-indent-mode' will turn off indentation adaptation.
     92 For details see the variable `org-adapt-indentation'."
     93   :group 'org-indent
     94   :type 'boolean)
     95 
     96 (defcustom org-indent-mode-turns-on-hiding-stars t
     97   "Non-nil means setting `org-indent-mode' will turn on `org-hide-leading-stars'."
     98   :group 'org-indent
     99   :type 'boolean)
    100 
    101 (defcustom org-indent-indentation-per-level 2
    102   "Indentation per level in number of characters."
    103   :group 'org-indent
    104   :type 'integer)
    105 
    106 (defcustom org-indent-post-buffer-init-functions nil
    107   "Hook run after org-indent finishes initializing a buffer.
    108 The function(s) in this hook must accept a single argument representing
    109 the initialized buffer."
    110   :group 'org-indent
    111   :package-version '(Org . "9.7")
    112   :type 'hook)
    113 
    114 (defface org-indent '((t (:inherit org-hide)))
    115   "Face for outline indentation.
    116 The default is to make it look like whitespace.  But you may find it
    117 useful to make it ever so slightly different."
    118   :group 'org-faces)
    119 
    120 (defvar org-indent--text-line-prefixes nil
    121   "Vector containing line prefixes strings for regular text.")
    122 
    123 (defvar org-indent--heading-line-prefixes nil
    124   "Vector containing line prefix strings for headlines.")
    125 
    126 (defvar org-indent--inlinetask-line-prefixes nil
    127   "Vector containing line prefix strings for inline tasks.")
    128 
    129 (defconst org-indent--deepest-level 50
    130   "Maximum theoretical headline depth.")
    131 
    132 (defun org-indent--compute-prefixes ()
    133   "Compute prefix strings for regular text and headlines."
    134   (setq org-indent--heading-line-prefixes
    135 	(make-vector org-indent--deepest-level nil))
    136   (setq org-indent--inlinetask-line-prefixes
    137 	(make-vector org-indent--deepest-level nil))
    138   (setq org-indent--text-line-prefixes
    139 	(make-vector org-indent--deepest-level nil))
    140   (when (> org-indent-indentation-per-level 0)
    141     (dotimes (n org-indent--deepest-level)
    142       (let ((indentation (if (<= n 1) 0
    143 			   (* (1- org-indent-indentation-per-level)
    144 			      (1- n)))))
    145         ;; Headlines line prefixes.
    146         (let ((heading-prefix (make-string indentation ?*)))
    147 	  (aset org-indent--heading-line-prefixes
    148 	        n
    149 	        (org-add-props heading-prefix nil 'face 'org-indent))
    150 	  ;; Inline tasks line prefixes
    151 	  (aset org-indent--inlinetask-line-prefixes
    152 	        n
    153 	        (cond ((<= n 1) "")
    154 		      ((bound-and-true-p org-inlinetask-show-first-star)
    155 		       (concat org-indent-inlinetask-first-star
    156 			       (substring heading-prefix 1)))
    157 		      (t (org-add-props heading-prefix nil 'face 'org-indent)))))
    158         ;; Text line prefixes.
    159         (aset org-indent--text-line-prefixes
    160 	      n
    161 	      (org-add-props
    162 	          (concat (make-string (+ n indentation) ?\s)
    163 		          (and (> n 0)
    164 			       (char-to-string org-indent-boundary-char)))
    165 	          nil 'face 'org-indent))))))
    166 
    167 (defsubst org-indent-remove-properties (beg end)
    168   "Remove indentations between BEG and END."
    169   (with-silent-modifications
    170     (remove-text-properties beg end '(line-prefix nil wrap-prefix nil))))
    171 
    172 ;;;###autoload
    173 (define-minor-mode org-indent-mode
    174   "When active, indent text according to outline structure.
    175 
    176 Internally this works by adding `line-prefix' and `wrap-prefix'
    177 properties, after each buffer modification, on the modified zone.
    178 
    179 The process is synchronous.  Though, initial indentation of
    180 buffer, which can take a few seconds on large buffers, is done
    181 during idle time."
    182   :lighter " Ind"
    183   (cond
    184    (org-indent-mode
    185     ;; mode was turned on.
    186     (setq-local indent-tabs-mode nil)
    187     (setq-local org-indent--initial-marker (copy-marker 1))
    188     (when org-indent-mode-turns-off-org-adapt-indentation
    189       ;; Don't turn off `org-adapt-indentation' when its value is
    190       ;; 'headline-data, just indent headline data specially.
    191       (or (eq org-adapt-indentation 'headline-data)
    192 	  (setq-local org-adapt-indentation nil)))
    193     (when org-indent-mode-turns-on-hiding-stars
    194       (setq-local org-hide-leading-stars t))
    195     (org-indent--compute-prefixes)
    196     (if (boundp 'filter-buffer-substring-functions)
    197 	(add-hook 'filter-buffer-substring-functions
    198 		  (lambda (fun start end delete)
    199 		    (org-indent-remove-properties-from-string
    200 		     (funcall fun start end delete)))
    201 		  nil t)
    202       ;; Emacs >= 24.4.
    203       (add-function :filter-return (local 'filter-buffer-substring-function)
    204 		    #'org-indent-remove-properties-from-string))
    205     (add-hook 'after-change-functions 'org-indent-refresh-maybe nil 'local)
    206     (add-hook 'before-change-functions
    207 	      'org-indent-notify-modified-headline nil 'local)
    208     (and font-lock-mode (org-restart-font-lock))
    209     (org-indent-remove-properties (point-min) (point-max))
    210     ;; Submit current buffer to initialize agent.  If it's the first
    211     ;; buffer submitted, also start the agent.  Current buffer is
    212     ;; pushed in both cases to avoid a race condition.
    213     (if org-indent-agentized-buffers
    214 	(push (current-buffer) org-indent-agentized-buffers)
    215       (push (current-buffer) org-indent-agentized-buffers)
    216       (setq org-indent-agent-timer
    217 	    (run-with-idle-timer 0.2 t #'org-indent-initialize-agent))))
    218    (t
    219     ;; Mode was turned off (or we refused to turn it on)
    220     (kill-local-variable 'org-adapt-indentation)
    221     (setq org-indent-agentized-buffers
    222 	  (delq (current-buffer) org-indent-agentized-buffers))
    223     (when (markerp org-indent--initial-marker)
    224       (set-marker org-indent--initial-marker nil))
    225     (when (local-variable-p 'org-hide-leading-stars)
    226       (kill-local-variable 'org-hide-leading-stars))
    227     (if (boundp 'filter-buffer-substring-functions)
    228 	(remove-hook 'filter-buffer-substring-functions
    229 		     (lambda (fun start end delete)
    230 		       (org-indent-remove-properties-from-string
    231 			(funcall fun start end delete))))
    232       (remove-function (local 'filter-buffer-substring-function)
    233 		       #'org-indent-remove-properties-from-string))
    234     (remove-hook 'after-change-functions 'org-indent-refresh-maybe 'local)
    235     (remove-hook 'before-change-functions
    236 		 'org-indent-notify-modified-headline 'local)
    237     (org-with-wide-buffer
    238      (org-indent-remove-properties (point-min) (point-max)))
    239     (and font-lock-mode (org-restart-font-lock))
    240     (redraw-display))))
    241 
    242 (defun org-indent-indent-buffer ()
    243   "Add indentation properties to the accessible part of the buffer."
    244   (interactive)
    245   (if (not (derived-mode-p 'org-mode))
    246       (error "Not in Org mode")
    247     (message "Setting buffer indentation.  It may take a few seconds...")
    248     (org-indent-remove-properties (point-min) (point-max))
    249     (org-indent-add-properties (point-min) (point-max))
    250     (message "Indentation of buffer set.")))
    251 
    252 (defun org-indent-remove-properties-from-string (string)
    253   "Remove indentation properties from STRING."
    254   (remove-text-properties 0 (length string)
    255 			  '(line-prefix nil wrap-prefix nil) string)
    256   string)
    257 
    258 (defun org-indent-initialize-agent ()
    259   "Start or resume current buffer initialization.
    260 Only buffers in `org-indent-agentized-buffers' trigger an action.
    261 When no more buffer is being watched, the agent suppress itself."
    262   (when org-indent-agent-resume-timer
    263     (cancel-timer org-indent-agent-resume-timer))
    264   (setq org-indent-agentized-buffers
    265 	(cl-remove-if-not #'buffer-live-p org-indent-agentized-buffers))
    266   (cond
    267    ;; Job done:  kill agent.
    268    ((not org-indent-agentized-buffers) (cancel-timer org-indent-agent-timer))
    269    ;; Current buffer is agentized: start/resume initialization
    270    ;; somewhat aggressively.
    271    ((memq (current-buffer) org-indent-agentized-buffers)
    272     (org-indent-initialize-buffer (current-buffer)
    273 				  org-indent-agent-active-delay))
    274    ;; Else, start/resume initialization of the last agentized buffer,
    275    ;; softly.
    276    (t (org-indent-initialize-buffer (car org-indent-agentized-buffers)
    277 				    org-indent-agent-passive-delay))))
    278 
    279 (defun org-indent-initialize-buffer (buffer delay)
    280   "Set virtual indentation for the buffer BUFFER, asynchronously.
    281 Give hand to other idle processes if it takes longer than DELAY,
    282 a time value."
    283   (with-current-buffer buffer
    284     (when org-indent-mode
    285       (org-with-wide-buffer
    286        (let ((interruptp
    287 	      ;; Always nil unless interrupted.
    288 	      (catch 'interrupt
    289 		(and org-indent--initial-marker
    290 		     (marker-position org-indent--initial-marker)
    291 		     (equal (marker-buffer org-indent--initial-marker)
    292 			    buffer)
    293 		     (org-indent-add-properties org-indent--initial-marker
    294 						(point-max)
    295 						delay)
    296 		     nil))))
    297 	 (move-marker org-indent--initial-marker interruptp)
    298 	 ;; Job is complete: un-agentize buffer.
    299 	 (unless interruptp
    300 	   (setq org-indent-agentized-buffers
    301 		 (delq buffer org-indent-agentized-buffers))
    302            (run-hook-with-args 'org-indent-post-buffer-init-functions buffer)))))))
    303 
    304 (defun org-indent-set-line-properties (level indentation &optional heading)
    305   "Set prefix properties on current line an move to next one.
    306 
    307 LEVEL is the current level of heading.  INDENTATION is the
    308 expected indentation when wrapping line.
    309 
    310 When optional argument HEADING is non-nil, assume line is at
    311 a heading.  Moreover, if it is `inlinetask', the first star will
    312 have `org-warning' face."
    313   (let* ((line (aref (pcase heading
    314 		       (`nil org-indent--text-line-prefixes)
    315 		       (`inlinetask org-indent--inlinetask-line-prefixes)
    316 		       (_ org-indent--heading-line-prefixes))
    317 		     level))
    318 	 (wrap
    319 	  (org-add-props
    320 	      (concat line
    321 		      (if heading (concat (make-string level ?*) " ")
    322 			(make-string indentation ?\s)))
    323 	      nil 'face 'org-indent)))
    324     ;; Add properties down to the next line to indent empty lines.
    325     (add-text-properties (line-beginning-position) (line-beginning-position 2)
    326 			 `(line-prefix ,line wrap-prefix ,wrap)))
    327   (forward-line))
    328 
    329 (defun org-indent-add-properties (beg end &optional delay)
    330   "Add indentation properties between BEG and END.
    331 
    332 When DELAY is non-nil, it must be a time value.  In that case,
    333 the process is asynchronous and can be interrupted, either by
    334 user request, or after DELAY.  This is done by throwing the
    335 `interrupt' tag along with the buffer position where the process
    336 stopped."
    337   (save-match-data
    338     (org-with-wide-buffer
    339      (goto-char beg)
    340      (forward-line 0)
    341      ;; Initialize prefix at BEG, according to current entry's level.
    342      (let* ((case-fold-search t)
    343 	    (limited-re (org-get-limited-outline-regexp))
    344 	    (level (or (org-current-level) 0))
    345 	    (time-limit (and delay (time-add nil delay))))
    346        ;; For each line, set `line-prefix' and `wrap-prefix'
    347        ;; properties depending on the type of line (headline, inline
    348        ;; task, item or other).
    349        (with-silent-modifications
    350 	 (while (and (<= (point) end) (not (eobp)))
    351 	   (cond
    352 	    ;; When in asynchronous mode, check if interrupt is
    353 	    ;; required.
    354 	    ((and delay (input-pending-p)) (throw 'interrupt (point)))
    355 	    ;; In asynchronous mode, take a break of
    356 	    ;; `org-indent-agent-resume-delay' every DELAY to avoid
    357 	    ;; blocking any other idle timer or process output.
    358 	    ((and delay (time-less-p time-limit nil))
    359 	     (setq org-indent-agent-resume-timer
    360 		   (run-with-idle-timer
    361 		    (time-add (current-idle-time) org-indent-agent-resume-delay)
    362 		    nil #'org-indent-initialize-agent))
    363 	     (throw 'interrupt (point)))
    364 	    ;; Headline or inline task.
    365 	    ((looking-at org-outline-regexp)
    366 	     (let* ((nstars (- (match-end 0) (match-beginning 0) 1))
    367 		    (type (or (looking-at-p limited-re) 'inlinetask)))
    368 	       (org-indent-set-line-properties nstars 0 type)
    369 	       ;; At an headline, define new value for LEVEL.
    370 	       (unless (eq type 'inlinetask) (setq level nstars))))
    371 	    ;; List item: `wrap-prefix' is set where body starts.
    372 	    ((org-at-item-p)
    373 	     (org-indent-set-line-properties
    374 	      level (org-list-item-body-column (point))))
    375 	    ;; Regular line.
    376 	    (t
    377 	     (org-indent-set-line-properties
    378 	      level
    379 	      (current-indentation)
    380 	      ;; When adapt indentation is 'headline-data, use
    381 	      ;; `org-indent--heading-line-prefixes' for setting
    382 	      ;; headline data indentation.
    383 	      (and (eq org-adapt-indentation 'headline-data)
    384 		   (or (org-at-planning-p)
    385 		       (org-at-clock-log-p)
    386 		       (looking-at-p org-property-start-re)
    387 		       (looking-at-p org-property-end-re)
    388 		       (looking-at-p org-property-re))))))))))))
    389 
    390 (defun org-indent-notify-modified-headline (beg end)
    391   "Set `org-indent-modified-headline-flag' depending on context.
    392 
    393 BEG and END are the positions of the beginning and end of the
    394 range of deleted text.
    395 
    396 This function is meant to be called by `before-change-functions'.
    397 Flag will be non-nil if command is going to modify or delete an
    398 headline."
    399   (when org-indent-mode
    400     (setq org-indent-modified-headline-flag
    401 	  (org-with-wide-buffer
    402 	   (goto-char beg)
    403 	   (save-match-data
    404 	     (or (and (org-at-heading-p) (< beg (match-end 0)))
    405 		 (re-search-forward
    406 		  (org-with-limited-levels org-outline-regexp-bol) end t)))))))
    407 
    408 (defun org-indent-refresh-maybe (beg end _)
    409   "Refresh indentation properties in an adequate portion of buffer.
    410 BEG and END are the positions of the beginning and end of the
    411 range of inserted text.  DUMMY is an unused argument.
    412 
    413 This function is meant to be called by `after-change-functions'."
    414   (when org-indent-mode
    415     (save-match-data
    416       ;; If a headline was modified or inserted, set properties until
    417       ;; next headline.
    418       (org-with-wide-buffer
    419        (if (or org-indent-modified-headline-flag
    420 	       (save-excursion
    421 		 (goto-char beg)
    422 		 (forward-line 0)
    423 		 (re-search-forward
    424 		  (org-with-limited-levels org-outline-regexp-bol)
    425                   (save-excursion
    426                     (goto-char end)
    427                     ;; Extend to headline if END is within its
    428                     ;; headline stars.
    429                     (line-end-position))
    430                   t)))
    431 	   (let ((end (save-excursion
    432 			(goto-char end)
    433 			(org-with-limited-levels (outline-next-heading))
    434 			(point))))
    435 	     (setq org-indent-modified-headline-flag nil)
    436 	     (org-indent-add-properties beg end))
    437 	 ;; Otherwise, only set properties on modified area.
    438 	 (org-indent-add-properties beg end))))))
    439 
    440 (provide 'org-indent)
    441 
    442 ;; Local variables:
    443 ;; generated-autoload-file: "org-loaddefs.el"
    444 ;; End:
    445 
    446 ;;; org-indent.el ends here