Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete trailng white space in emacs?

Tags:

emacs

I have a text file that has fixed length lines, padded by trailing spaces like:

hello world                 ↩
this is some other line     ↩
x                           ↩

and I want to remove the trailing spaces on each line so it looks like

hello world↩
this is some other line↩
x↩

Is it possible to write an emacs macro that can solve this?

Edit: the lines can have any arbitrary number of spaces in it before the trailing spaces at the end, so

hi     world                ↩

can be a valid line in this file.

like image 337
Davis Dimitriov Avatar asked Oct 12 '11 21:10

Davis Dimitriov


People also ask

How do I remove trailing spaces from a file?

Method One: sed A simple command line approach to remove unwanted whitespaces is via sed . The following command deletes all spaces and tabs at the end of each line in input. java . If there are multiple files that need trailing whitespaces removed, you can use a combination of find and sed commands.

How do you fix a trailing whitespace error?

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file. In emacs: C-M-% <space> + $ then press return twice.

How do I get rid of trailing space in Xcode?

Simply select all, cut, paste back and it auto formats. #swift. Type a few lines and try to select them with the mouse - that's the moment Xcode will decide to remove the trailing spaces which for some reason immediately removes the selection again.


1 Answers

There is an emacs command delete-trailing-whitespace that gets rid of whitespace after last character. If you run it without any region marked, it cleans up the whole buffer. If you have an active region, only the lines in the region are cleaned.

A lot of people add the following code to their .emacs, so that whenever they save a file, all trailing whitespace is cleaned up:

(add-hook 'before-save-hook
          'delete-trailing-whitespace)
like image 150
vhallac Avatar answered Sep 24 '22 01:09

vhallac