Skip to main content
3 of 3
added 643 characters in body
N.N.
  • 2k
  • 16
  • 18

If you prefix a function with C-h f you can read documentation for it. If you do it for fill-region it shows, among other things:

The `fill-column' variable controls the width. 

And if you check the Emacs manual on Fill commands you can read:

The maximum line width for filling is specified by the buffer-local variable fill-column. The default value (see Locals) is 70. The easiest way to set fill-column in the current buffer is to use the command C-x f (set-fill-column). With a numeric argument, it uses that as the new fill column. With just C-u as argument, it sets fill-column to the current horizontal position of point.

This explains how C-u 70 M-x fill-region works. It also shows that the width to fill with can be set via C-x f. Thus, it may not be necessary to write a function that asks for a parameter, i.e. you could use C-x f and fill-region instead.

If you still want new functions to do this you can use the following:

(defun fill-region-ask-width (fill-width) "Asks for a width and fills the region to it" (interactive "nFill region to column: ") (fill-region-width fill-width)) (defun fill-region-width-70 () "Fills the region with width 70" (interactive) (fill-region-width 70)) (defun fill-region-width (fill-width) "Fills the region with the given width" (set-fill-column fill-width) (fill-region (region-beginning) (region-end))) 

The functions are explained by their doc strings but here are some more notes:

  • fill-region-ask-width takes one argument which it gets by asking the user and it treats that number as an integer (n) and passes it to fill-region-prompt-width.
  • fill-region-width-70 merely has a hard-coded number that it passes to fill-region-prompt-width.
  • fill-region-width is a helper function to modularize what the other two functions have in common. It is not defined as interactive so it is not possible to call via M-x. It sets fill-column to the given argument and fills the region`.

For learning how to write Emacs functions and binding them to keys see Learn Elisp For Emacs: Lesson 4-2 - Adding Custom Functions To Emacs.

N.N.
  • 2k
  • 16
  • 18