Skip to content

Instantly share code, notes, and snippets.

@j-cr
Last active November 2, 2020 20:35
Show Gist options
  • Save j-cr/2573e26f3ef05c94f7e88cbd2a9cb7b2 to your computer and use it in GitHub Desktop.
Save j-cr/2573e26f3ef05c94f7e88cbd2a9cb7b2 to your computer and use it in GitHub Desktop.
(defun narrow-or-widen-dwim (p)
;; fixed to behave correctly in org-src buffers; taken from:
;; https://lists.gnu.org/archive/html/emacs-orgmode/2019-09/msg00094.html
"Widen if buffer is narrowed, narrow-dwim otherwise.
Dwim means: region, org-src-block, org-fixed-width-region,
org-table-field, org-subtree, or defun, whichever applies
first. Narrowing to:
- org-src-block calls `org-edit-src-code'
- org-fixed-width-region calls `org-edit-fixed-width-region'
- org-table-field calls `org-table-edit-field'
With prefix P, don't widen, just narrow even if buffer is already
narrowed. If called with a prefix on a table field, just make the
full field visible so that it can be edited in place."
(interactive "P")
(declare (interactive-only))
(cond
;; exit:
((and (not p) (buffer-narrowed-p))
(widen))
((and (not p) (org-src-edit-buffer-p))
(org-edit-src-exit))
((and (not p) (equal (buffer-name) "*Org Table Edit Field*"))
(orgtbl-ctrl-c-ctrl-c nil))
((and (not p) (separedit-in-edit-buffer-p))
(separedit-commit))
;; enter:
((region-active-p)
(narrow-to-region (region-beginning) (region-end)))
((derived-mode-p 'org-mode)
(cond ((ignore-errors (org-edit-src-code) t))
((ignore-errors (org-edit-fixed-width-region) t))
((org-at-table-p) (call-interactively 'org-table-edit-field) t)
((ignore-errors (org-narrow-to-block) t))
((ignore-errors (org-narrow-to-element) t))
(t (org-narrow-to-subtree))))
((derived-mode-p 'latex-mode)
(LaTeX-narrow-to-environment))
((ignore-errors (separedit) t))
(t (narrow-to-defun))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment