From 43FoldersWiki

Jump to: navigation, search

[edit] Editing files that use non-Unix end-of-line characters

Sometimes, you open a text file and the line formatting is all wrong and there are loads of annoying '^M' characters spread all throughout it. If you're using vim on a Mac, you are likely to encounter this problem a lot because it is caused when a Mac-formatted text file is opened in vim because vim prefers text files that are Unix-formatted. You could also run into similar problems with Windows-formatted text files. Luckily, this is an easy thing to deal with in vim.

Actually, in current versions of vim, it will read and edit files like these just fine. You should never see those extra '^M' characters any longer. The editor should come up with a buffer status line message that says [dos] letting you know what format the file is in. However, the file will not change formats unless you use solution #1 below. vim has no trouble using solution #1 that I know of.

Solution #1: Type :set fileformat unix and hit enter while in edit (not insert) mode. This should reformat the file for you and solve the problem.

Solution #2: Sometimes solution #1 doesn't work. So it is not recommended that you use it. Instead, use global search and replace to fix the files. While in edit mode, type :%s/\r/\r/g and hit enter. This will replace all Mac-formatted carriage returns with unix-formatted newlines. This seems counter-intuitive since you're telling the editor to replace carriage returns with carriage returns, but it works because of how vim interprets a carriage return command. Using the same fix to change a Windows file to a Unix file would require a different pattern, like this: :%s/^M//g (be sure to use ctrl-M when typing the ^M in the pattern, don't type a '^' character followed by a 'M' character).

If typing that pattern in every time you need it seems a bit much, just map it to a key command. For example, put the following lines in your .vimrc file in your home directory:

nnoremap M :%s/\r/\r/g <CR>
vnoremap M :%s/\r/\r/g <CR>
nnoremap W :%s/^M//g <CR> # Remember to type the ^M with ctrl-M and not with '^' followed by 'M'
vnoremap W :%s/^M//g <CR> 

Now the command to convert Mac text files into Unix text files is mapped to the uppercase 'M' in edit mode, so you can just type that command the instant you load the file and see that it's broken. Similarly, the command to convert Windows text files to Unix files is mapped to the uppercase 'W'. Additionally, if you use the commands while you have selected text in the file, the changes will only occur to that portion of the file that you have selected.

If you want to better understand these commands, use vim's built-in help with these commands:

:help mapping
:help substitute
:help pattern
Personal tools