Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a buffer be duplicated in Vim?

Tags:

vim

copy

buffer

I'm looking for a way to make a new buffer which is a copy of the current buffer.

I could then do something like the following to duplicate the current tab to a new tab in gVim for example:

:let b = bufnr("%") | tabnew | execute 'buffer' b | *duplicate*

However, this question isn't specific to tabs or gVim; I may want to duplicate the buffer after a split command or a vert diffsplit command. (Actually, vert diffsplit was the first instance that I realised I wanted to duplicate buffers.)

Ideally I also want to retain as much of the original buffer and window state as possible, including cursor position, with the exception that the original buffer read-only state is disregarded and the new buffer is always writeable.

Currently when I encounter this task, I type ggyG, open or move to the new buffer, then type Vp, but not only do I loose my cursor position for the new window, the copy command I use necessitates loosing the position in the original window as well. The process can surely be streamlined into a single command.

like image 641
James Haigh Avatar asked Oct 01 '22 10:10

James Haigh


1 Answers

The following sequence of commands should provide a good starting point…

  1. in the original buffer:

    :%y
    :let my_view = winsaveview()
    :let my_ft = &filetype
    :new
    
  2. in the new buffer:

    :execute "setf " . my_ft
    :0put
    :call winrestview(my_view)
    

Note that the "state" you want to duplicate is not buffer-specific but window-specific.

like image 184
romainl Avatar answered Oct 05 '22 12:10

romainl