If I use (thing-at-point 'paragraph) (or mark-paragraph, for that matter), the selection isn't necessarily aware only about the empty lines. Especially, with lists and code blocks in org-mode.

So, I need a function which returns the bounds which include everything between surrounding blank lines. How would I do that?


So, to clarify, if I do (thing-at-point 'paragraph) here:

#+BEGIN_SRC python
x = 1
y = 2

I get:

"x = 1
y = 2
#+END_SRC" <font info>
  • Can you clarify? Eg give an example where this does not do what you want. – JeanPierre May 26 '19 at 19:50
  • @JeanPierre sure, edited the answer. – user3496846 May 26 '19 at 19:59

Here is a function that returns the text between two surrounding blank lines:

(defun region-between-surrounding-blank-lines ()
  (let ((beg nil) (end nil))
      (re-search-backward (rx bol (* blank) eol))
      (setq beg (point))
      (re-search-forward (rx bol (* blank) eol))
      (setq end (- (point) 1)))
    (buffer-substring-no-properties beg end)))

Edit: Executing the function above raises an error if there are no two blank lines in the buffer. Here is an alternative version where text is selected from the beginning/end of the buffer if there are no blank line above/below the current position:

(defun region-between-surrounding-blank-lines ()
  (let ((beg nil) (end nil))
      (if (re-search-backward (rx bol (* blank) eol) nil t nil)
        (setq beg (point))
        (setq beg (point-min)))
      (if (re-search-forward (rx bol (* blank) eol) nil t nil)
        (setq end (- (point) 1))
        (setq end (point-max))))
    (buffer-substring-no-properties beg end)))

Hopefully StarBug gave you an answer to your literal question about stuff between newlines.

Your clarification suggests that you are actually looking for org-element-context.

That function gives you the org element at point which can be a source block.

The returned element has properties like its bounds (:begin and :end) and its contents (:value).

The following Elisp code makes (thing-at-point 'org-src-block) work. You can use that instead of (thing-at-point 'paragraph) if you are actually looking for the source block.

(defun org-src-block-at-point ()
  "Return source block at point as string."
  (let ((el (org-element-context)))
    (when (eq (org-element-type el) 'src-block)
       (org-element-property :begin el)
     (goto-char (org-element-property :end el))
     (skip-chars-backward "\n[:space:]")

;; Enable (thing-at-point 'org-src-block):
(put 'org-src-block 'thing-at-point #'org-src-block-at-point)
  • This will come in handy, thank you! – user3496846 May 27 '19 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.