3

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)))
  • What does this do that is different from 'M-x fill-paragraph'? – Tyler Nov 5 '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 5 '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 5 '15 at 18:37
  • @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 5 '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 5 '15 at 18:54
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).

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.