6

When editing human language text and moving text fragments around, I frequently run into the problem that whitespace moved at the beginning or end of a fragment doesn't fit into the new position. For example, consider this paragraph:

This is the first sentence.  This is the second sentence.  These
three sentences are the whole paragraph.

If I move the last sentence before the first one by kill+yank, I have either leading or trailing whitespace. A similar problem occurs in enumerations.

Another use case is if I want to insert a single word or expression which is in the kill ring without any trailing or leading whitespace. For example, consider the word "very" in the kill ring, and the following sentence:

Such a minor mode would be useful.

After yanking, this may erroneously become:

Such a minor mode would bevery useful.

Is there a way to have white space in human texts adjusted automatically?

Torsten Bronger
  • 329
  • 2
  • 6

2 Answers2

2

Here's a function, delete-leading-whitespace-on-line to do as the name suggests:

(defun delete-leading-whitespace-on-line ()
  "Delete whitespace at the beginning of the current line."
  (interactive)
  (let ((start (line-beginning-position))
        (end (line-end-position)))
    (save-excursion
      (delete-whitespace-rectangle start end nil))))

For trailing whitespace, I use M-x delete-trailing-whitespace.

To trigger these after yanks, you could do something like:

(defun yank-and-trim-whitespace ()
  "Yank and then trim whitespace on the line."
  (interactive)
  (yank)
  (delete-leading-whitespace-on-line)
  (delete-trailing-whitespace))

and bind it like:

(global-set-key "\C-y" 'yank-and-trim-whitespace)

You might also like to try Steve Purcell's whitespace-cleanup-mode, a minor mode that:

will intelligently call whitespace-cleanup before buffers are saved.

PS His GitHub account is a treasure trove of Emacs goodies.

yurrriq
  • 131
  • 5
2

This seems to do what you have asked. By contrast if there is already extra white spaces, it keeps them as before.

  (defun yank-and-adjust-whitespace ()
  (interactive)
  (if (equal (char-after) ?\s)
      (progn
        (insert " ")
        (yank))
    (if (eolp) (if (bolp) (yank)
        (if (equal (char-before) ?\s)
            (yank)
          (insert " ")
          (yank)))
      (yank)
      (insert " "))))

Like the answer of Eric Bailey you can associate the below shortcut.

(global-set-key "\C-y" 'yank-and-adjust-whitespace)

Using eolp/bolp was borrowed from https://emacs.stackexchange.com/a/13741/.

Name
  • 7,689
  • 4
  • 38
  • 84
  • @wasamasa thanks for editing, I saw that you have changed `? ` to`?\s`. It seems that both work. I am interested to know about their differences. – Name Jul 06 '15 at 12:30
  • 1
    Correct, both are equivalent. The manual recommends `?\s` though because it looks a lot less confusing than `? ` and ensures that you meant to match a space instead of mistyping. – wasamasa Jul 06 '15 at 12:42