Emacs: Open a buffer with all lines between lines X to Y from a huge file

emacslarge files

In the same spirit as this other question: cat line X to line Y on a huge file:

Is there a way to open from within Emacs (and
show on a buffer) a given set of lines (e.g. all lines between line X and Y) from a huge text file?

E.g. Open and show in a buffer all lines between lines 57890000 and 57890010 from file huge.txt

Update:
I am interested in a solution that at least can open the lines in read-only (just for display purposes), although it would be great if I can also edit the lines (and save to the original file).

Best Answer

If you want to open the whole file (which requires ), but show only part of it in the editor window, use narrowing. Select the part of the buffer you want to work on and press C-x n n (narrow-to-region). Say “yes” if you get a prompt about a disabled command. Press C-x n w (widen) to see the whole buffer again. If you save the buffer, the complete file is selected: all the data is still there, narrowing only restricts what you see.

If you want to view a part of a file, you can insert it into the current buffer with shell-command with a prefix argument (M-1 M-!); run the appropriate command to extract the desired lines, e.g. <huge.txt tail -n +57890001 | head -n 11.

There is also a Lisp function insert-file-contents which can take a byte range. You can invoke it with M-: (eval-expression):

(insert-file-contents "huge.txt" nil 456789000 456791000)

Note that you may run into the integer size limit (version- and platform-dependent, check the value of most-positive-fixnum).

In theory it would be possible to write an Emacs mode that loads and saves parts of files transparently as needed (though the limit on integer sizes would make using actual file offsets impossible on 32-bit machines). The only effort in that direction that I know of is VLF (GitHub link here).

Related Question