4

I am new to emacs and would like to make a simple function to automate a series of commands I use repeatedly.

In auto-fill-mode after I edit the text I often need to re-wrap the lines. (I am writing in LaTeX with each sentence starting on a new line.) To do this I type M-a,C-SPC,M-e,M-q. This is equivalent to backward-sentence, set-mark-command, forward-sentence, fill-region.

How can I wrap these together in one simple command?

This is my non-working attempt:

(defun fill-sentence()
  "In auto-fill mode, select current sentence and re-wrap it."
  (interactive)
  ((backward-sentence)
   (set-mark-command)
   (forward-sentence)
   (fill-region)))
musarithmia
  • 143
  • 5
  • What does this do that is different from 'M-x fill-paragraph'? – Tyler Nov 05 '15 at 17:38
  • @Tyler The goal was to fill only the current sentence.`fill-paragraph` trims newlines to adjust the whole paragraph. – musarithmia Nov 05 '15 at 17:41
  • So it does! Out of curiosity, why don't you want the whole-paragraph filled? Playing around with Jonathan's answer, I see that filling one sentence often 'unfills' the next one. – Tyler Nov 05 '15 at 18:37
  • 1
    @Tyler I haven't seen that effect yet. I'm writing in LaTeX with a new line for each sentence. I have used `visual-line-mode` in the past but am experimenting with `auto-fill-mode` instead to see if there are any advantages. – musarithmia Nov 05 '15 at 18:46
  • 1
    Thanks, I understand now. If each sentence starts on a new line, `fill-sentence` won't change adjacent sentences the way it does in my tests on normal paragraphs. – Tyler Nov 05 '15 at 18:54

1 Answers1

4

Based on the docstrings of the commands, you probably want something along the lines of:

(defun fill-sentence ()
  (interactive)
  ;; optional 
  ;; (save-excursion
  (backward-sentence)
  (push-mark)
  (forward-sentence)
  (fill-region (point) (mark))
  ;; )
  )

The optional save-excursion (and commented )) will keep the point where you started (so can be used mid-change to keep track of wrapping without breaking flow).

Jonathan Leech-Pepin
  • 4,307
  • 1
  • 19
  • 32