Command line: VIM

Vim for .NET – Move type to another file

When I started my journey with VIM for .NET, I tried to find VIM alternatives of common shortcuts/refactorings that I used in Visual Studio. Surprisingly I noticed that most of them were already there (Searching, Go To Definition, Find usages, create class etc). The one I had a real problem with was “Move type to another file”. I really like the idea that I can create all the types in one file and then use some shortcut (with ReSharper: Alt + Enter) to distribute them to their own files. As I could not find any existing plugin (which is really strange) I took it as a good time to try myself in writing vimscript. It turned out that it was pretty easy exercise. Here you can find the script that you can append to _vimrc to enable the feature.


function! ExtractClassToFile() abort
    " copy class name
    execute "normal! ?^.*\\sclass\\s\0/class\wviwy"
    " and store for future use (filename)
    let className = getreg('"')

    " cut class code and store it inside default register
    execute "normal! ?^.*class\V/{\%x"	
    " and store for future use
    let classText = getreg('"')
   
    " copy namespace + usings
    execute "normal! ggv/namespace \/{\ly"
    let usingAndNamespace = getreg('"')
    
    " get filename for the new file
    let currFileLocation = expand('%:p:h')
    let newFileName = "\\".className.".cs"
    let newFileFullPath = currFileLocation . newFileName
   
    " open the new file
    execute "e ".newFileFullPath

    " render the file
    let failed = append(line('$'), split(usingAndNamespace, '\n'))
    let failed = append(line('$'), split(classText, '\n'))
    let failed = append(line('$'), '}')

    " remove empty line in the beginning
    execute "normal! dd"
    " save
    execute "w"
endfunction

noremap ef :call ExtractClassToFile()
Advertisements

2 thoughts on “Vim for .NET – Move type to another file

  1. Nice job, but I think it is easier to use VIM plugin on visual studio. In this way you will save power of VS as an IDE.

    1. I’ve been using VsVim for the last 2 years and now I cannot imagine working with VS without it. But still there are things that I prefer in VIM alone:
      – better macro recording – hard to use in VS
      – it’s lightweight
      – extensibility (writing extension is sometimes a minute or two)
      – less debugging
      – closer to terminal and automation
      …and more 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s