Циклическая видимость исходного блока в организационном режиме

Я пытаюсь добавить исходные блоки в дерево циклов видимости. По сути, я хочу, чтобы исходный блок рассматривался как дочерний элемент его заголовка. Рассмотрим следующий документ организационного режима:

* Heading 1
** Heading 2
#+BEGIN_SRC R
print("hello world")
#+END_SRC
** Heading 3

Я хотел бы иметь возможность нажимать TAB в первом заголовке, чтобы переключаться между складыванием различных частей, включая исходный блок. В настоящее время в организационном режиме, похоже, есть средства для сворачивания исходного блока, потому что я могу свернуть это, если перейду к #+BEGIN_SRC R и нажму вкладку, но, похоже, это не обрабатывается в глобальном цикле. Любые предложения, чтобы добавить его?

Спасибо!


person Rob Richmond    schedule 25.08.2014    source источник
comment
Я не уверен, встроено ли это, но вот ссылка на модификацию, которую я сделал для html-блоков и сносок: stackoverflow. com/a/21594242/2112489 См. также этот связанный поток: stackoverflow.com/a/21563210/2112489   -  person lawlist    schedule 25.08.2014
comment
Хорошо, я просматриваю ваш код и пытаюсь собрать его воедино. Поскольку блоки BEGIN_SRC уже свернуты, все, что мне нужно сделать, это изменить org-cycle-internal-local аналогично тому, что вы сделали. Или я что-то упускаю?   -  person Rob Richmond    schedule 25.08.2014
comment
Я бы попробовал переменную, упомянутую во второй ссылке, и посмотрел, поможет ли это, прежде чем рассматривать первую идею. Я должен был разместить вторую ссылку первой по времени. . . Прости.   -  person lawlist    schedule 25.08.2014
comment
Эта переменная сворачивает блоки, но циклирование блоков по-прежнему не работает. Я попытаюсь собрать что-нибудь из вашего кода. Спасибо!   -  person Rob Richmond    schedule 25.08.2014


Ответы (1)


Это небольшая модификация кода, содержащегося в ссылке, упомянутой в моем первом комментарии выше: https://stackoverflow.com/a/21594242/2112489

Все, что я сделал, это заменил регулярное выражение begin/end html на регулярное выражение SRC. Идите вперед и дать ему вихрь и посмотреть, если это то, что вы ищете. Я оставил там свою предыдущую модификацию сноски.

(require 'org)

(defalias 'org-cycle-hide-drawers 'lawlist-block-org-cycle-hide-drawers)

(defun lawlist-block-org-cycle-hide-drawers (state)
  "Re-hide all drawers, footnotes or html blocks after a visibility state change."
  (when
    (and
      (derived-mode-p 'org-mode)
      (not (memq state '(overview folded contents))))
    (save-excursion
      (let* (
          (globalp (memq state '(contents all)))
          (beg (if globalp (point-min) (point)))
          (end
            (cond
              (globalp
                (point-max))
              ((eq state 'children)
                (save-excursion (outline-next-heading) (point)))
              (t (org-end-of-subtree t)) )))
        (goto-char beg)
        (while
          (re-search-forward
            ".*\\[fn\\|^\\#\\+BEGIN_SRC.*$\\|^[ \t]*:PROPERTIES:[ \t]*$" end t)
          (lawlist-org-flag t))))))

(defalias 'org-cycle-internal-local 'lawlist-block-org-cycle-internal-local)

(defun lawlist-block-org-cycle-internal-local ()
  "Do the local cycling action."
  (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
    (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 (1- (org-end-of-subtree t t))))
        (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)))))
      (beginning-of-line 2)
      (if (featurep 'xemacs)
        (while
            (and
              (not (eobp))
              (get-char-property (1- (point)) 'invisible))
          (beginning-of-line 2))
        (while
            (and
              (not (eobp))
              (get-char-property (1- (point)) 'invisible))
          (goto-char (next-single-char-property-change (point) 'invisible))
          (and
            (eolp)
            (beginning-of-line 2))))
      (setq eol (point)))
    (cond
      ((= eos eoh)
        (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)
          (if (outline-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))))
        (unless (org-before-first-heading-p)
          (run-hook-with-args 'org-pre-cycle-hook 'children))
        (if (org-at-item-p)
          ;; then
          (org-list-set-item-visibility (point-at-bol) struct 'children)
          ;; else
          (org-show-entry)
          (org-with-limited-levels (show-children))
          (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)))
                  (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
                    (org-list-get-all-items (point) struct prevs))
                  (goto-char (if (< end eos) end eos)))))))
        (org-unlogged-message "CHILDREN")
        (save-excursion
          (goto-char eos)
          (outline-next-heading)
          (if (outline-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)))
        (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)))
      ((eq org-cycle-subtree-status 'subtree)
        (org-show-subtree)
        (message "ALL")
        (setq org-cycle-subtree-status 'all))
      (t
        (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))))))

(defun lawlist-org-flag (flag)
  "When FLAG is non-nil, hide any of the following:  html code block;
footnote; or, the properties drawer.  Otherwise make it visible."
  (save-excursion
    (beginning-of-line 1)
    (cond
      ((looking-at ".*\\[fn")
        (let* (
          (begin (match-end 0))
          end-footnote)
          (if (re-search-forward "\\]"
                (save-excursion (outline-next-heading) (point)) t)
            (progn
              (setq end-footnote (point))
              (outline-flag-region begin end-footnote flag))
            (user-error "Error beginning at point %s." begin))))
      ((looking-at "^\\#\\+BEGIN_SRC.*$\\|^[ \t]*:PROPERTIES:[ \t]*$")
        (let* ((begin (match-end 0)))
          (if (re-search-forward "^\\#\\+END_SRC.*$\\|^[ \t]*:END:"
                (save-excursion (outline-next-heading) (point)) t)
            (outline-flag-region begin (point-at-eol) flag)
            (user-error "Error beginning at point %s." begin)))))))

(defun lawlist-toggle-block-visibility ()
"For this function to work, the cursor must be on the same line as the regexp."
(interactive)
  (if
      (save-excursion
        (beginning-of-line 1)
          (looking-at
            ".*\\[fn\\|^\\#\\+BEGIN_SRC.*$\\|^[ \t]*:PROPERTIES:[ \t]*$"))
    (lawlist-org-flag (not (get-char-property (match-end 0) 'invisible)))
    (message "Sorry, you are not on a line containing the beginning regexp.")))
person lawlist    schedule 26.08.2014
comment
Прекрасно работает. Большое спасибо. - person Rob Richmond; 26.08.2014
comment
Рад помочь. Код сноски предусматривает только одну (1) сноску на заголовок, и его необходимо улучшить. Пожалуйста, не стесняйтесь удалить код сноски или улучшить его, если хотите. - person lawlist; 26.08.2014
comment
Это вводит некоторое странное поведение «зависимого переключателя света»: хотя вы можете развернуть блок кода из его заголовка, вы больше не можете развернуть его из строки блока исходного кода. но если вы попробуете один раз, то развертывание из заголовка больше не работает, пока вы снова не «переключите» его на строку блока кода. По крайней мере, это то, что я испытываю - person TNT; 16.06.2016