1

I want to get the whole buffer contents as a single string. Currently I'm doing this:

let line_ending = "\n"
let text = join(getline(1, '$'), line_ending).line_ending

But this assumes the line ending. If this is the best approach, how can I find out what the line ending actually is?

Or is there a better way to get the actual buffer contents?

  • Why do you need it as a single string? NUL characters will be problematic. – Antony Jun 15 '17 at 11:38
  • To send it to another process. – Andy Stewart Jun 15 '17 at 12:06
  • You could send a list of lines, or the filename. – Antony Jun 15 '17 at 12:13
  • A list wouldn't contain the line endings. The buffer might not be saved and therefore not have a file, or it might have changes which its file doesn't. – Andy Stewart Jun 15 '17 at 12:14
  • 1
    The fileformat option looks like it gives me the buffer's line endings (assuming they are not mixed). – Andy Stewart Jun 15 '17 at 14:23
3

It's possible to directly put the content of the current buffer into a register (and from here into a variable) thanks to :%y (:yank takes an optional register name).

However, after a test on a file in dos format, I've seen that my register contained characters of code 10 for newlines. The test being done with :echo map(split(@", '\zs'), 'char2nr(v:val)').

I'm not sure why you want to extract the binary content of the buffer though -- IOW, I'm not sure to see why you want to keep the original line ending.

1

The 'fileformat' setting control the end-of-line character that Vim uses. There are three possible values:

  • unix\n
  • dos\r\n
  • mac\r (this is very archaic and only applies to the pre-OSX "classic" MacOS of the 80s and 90s).

In VimScript this would be:

if &fileformat == 'unix'
    let line_ending = "\n"
elseif &fileformat == 'dos'
    let line_ending = "\r\n"
elseif &fileformat == 'mac'
    let line_ending = "\r"
else
    echoerr "unknown value for the 'fileformat' setting: " . &fileformat
endif

Or a shorter version:

let line_ending = {"unix": "\n", "dos": "\r\n", "mac": "\r"}[&fileformat]
  • Thanks! I realised the same thing yesterday and wrote the exact same code you provided :) – Andy Stewart Jun 16 '17 at 8:20

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.