0

I've need a function which convert a paragraph into the line, sort each space separated set of characters and fill it back to paragraph.

In:

Supposedly there are over one million words in the English Language. We trimmed some fat to take away really odd words and determiners. Then we grabbed the most popular words and built this word randomizer. Just keep clicking generate chances are you won't find a repeat

out:

English Just Language Supposedly Then We a and and are are. away built chances clicking determiners fat find generate grabbed in keep million. most odd one over popular randomizer really repeat some t take the. the there this to trimmed we won word'words words words you

Trying to adopt function from EmacsWiki

   (defun sort-words (reverse beg end)
      "Sort words in region alphabetically, in REVERSE if negative.
    Prefixed with negative \\[universal-argument], sorts in reverse.

    The variable `sort-fold-case' determines whether alphabetic case
    affects the sort order.

    See `sort-regexp-fields'."
      (interactive "*P\nr")
      (sort-regexp-fields reverse "\\w+" "\\&" beg end))
1

Here's a function which, sorts the words, then calls fill-paragraph on them.

(defun sort-words (start end)
  (interactive "r")
  (let ((text (buffer-substring start end)))
    (delete-region start end)
    (insert (with-temp-buffer
              (insert (replace-regexp-in-string "\s+" "\n" text))
              (sort-lines nil (point-min) (point-max))
              (fill-paragraph)
              (buffer-string)))))

On your input, this is what is returned:

English Just Language.  Supposedly Then We a and and are are away
built chances clicking determiners.  fat find generate grabbed in keep
million most odd one over popular randomizer.  really repeat some take
the the there this to trimmed we won't word words words words you

It's slightly different from your example in a few ways.

  1. It keeps punctuation at the word that the punctuation started as; "Language." has a period. Your example seems to keep punctuation in the same "place"; there's a period after the 11th word in the input ("Language"), and there's a period after the 11th word in the output ("are"). Note that "Language" does not have a period in your example output; "are" does not have a period in your example input. What do you want with punctuation?
  2. It fills the paragraph into different lines, as you request, while your example output does not. Is that what you want?
  3. Because it uses fill-paragraph, there are two spaces after sentences end.
  • Great, thanks! I've just altered (fill-paragraph) to (fill-region (point-min) (point-max)) and it's want I wanted to achieve now. – Hellseher Aug 3 '18 at 23:42

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.