Question

I am defining a major mode that works on paragraphs of the following nature:

: Identifier
1. some text
2. ...
3. some more text

: New Identifier

: Another Identifier
some text

I want to write a defun called get-paragraphs that will return a list that looks like:

(   ("Identifier", ("1. some text", "2. ...", "3. some more text")), 
    ("New Identifier", ()),
    ("Another Identifier", ("some text"))
)

How do I go about cutting up the text like this in Emacs Lisp:

Is there a function to iterate through them (and subsequently chop them up to my liking)? Should I use regular expressions? Is there an easier way?

Was it helpful?

Solution

You should iterate over the buffer and collect your text (untested):

(defun get-paragraphs ()
  (save-excursion
    (goto-char (point-min))
    (let ((ret '()))
      (while (search-forward-regexp "^: " nil t)
        (let ((header (buffer-substring-no-properties (point) (line-end-position)))
              (body '()))
          (forward-line)
          (while (not (looking-at "^$"))
            (push (buffer-substring-no-properties (point) (line-end-position)) body)
            (forward-line))
          (push (cons header (list (reverse body))) ret)))
      (nreverse ret))))

OTHER TIPS

Here, take this Lisp code:

(defun chopchop ()
  (mapcar 
   (lambda (x)
     (destructuring-bind (head &rest tail)
         (split-string x "\n" t)
       (list head tail)))
   (split-string (buffer-substring-no-properties
                  (point-min)
                  (point-max)) "\n?: *" t)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top