5

This question already has an answer here:

I normally like to keep swap files on, but if I am editing huge log files I usually don't want them. Since I am just viewing the files in vim, it is unnecessary to have a swap file. I could just run set noswapfile for *.log files, but I was wondering if I could just disable it if the file is larger than a specified amount.

marked as duplicate by Martin Tournoij May 31 '15 at 22:19

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5

You can combine autocommands with the getfsize(file) function to automatically disable options for large files.

" A global variable that contains the size of which a file is considered
" large.  In this case, it is 10 megabytes.
let g:large_file = 1024 * 1024 * 10

" This autocmd runs before reading the file into the buffer.  It
" gets the file that the autocmd is running on by running expand on
" <afile>, which is short for the path to the file that the autocmd
" is running on.  Then, it gets the size of the file running
" getfsize on the file and sees if it is larger than the size
" specified in g:large_file.  If it is, it disables the swap file.
autocmd BufReadPre * let f=expand("<afile>") | if getfsize(f)
            \ > g:large_file | set noswapfile | endif

Note that you can add any other options you want where set noswapfile is to improve performance on large files. If you have a lot of them, you might want to create a function which sets all of them, and then add a call to that function where set noswapfile is.

Related to performance when editing large files, here are some options that can help:

  • :help 'bufhidden'
  • :help 'buftype'
  • :help 'eventignore'
  • :help 'undolevels'

For instance, those options can be set to the below for better performance:

setlocal bufhidden=unload " (save memory when other file is viewed)
setlocal buftype=nowrite " (is read-only)
setlocal eventignore+=Filetype " (ignores autocommands with FileType as their trigger event)
setlocal undolevels=-1 " (no undo possible)

Related help topics:

  • :help getfsize()
  • :help expand()
  • :help <afile>

I got some of this information from http://vim.wikia.com/wiki/Faster_loading_of_large_files which has useful information on performance when editing large files.

  • There's a plugin floating around that does all this automatically and more (IIRC), but I can't remember its name right now. – lcd047 May 31 '15 at 21:51
  • I imagine that there would be, the vim tip pointed to one at vim.org/scripts/script.php?script_id=1506 In fact, that plugin was based on that vim tip, – EvergreenTree May 31 '15 at 22:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.