Get the file name without file extension in Vim function.

前端 未结 4 650
梦毁少年i
梦毁少年i 2021-01-30 10:51

I want to get the file name without the file extension in Vim.

I wrote the following functions in my .vimrc file for compile and run the Java program.

4条回答
  •  佛祖请我去吃肉
    2021-01-30 11:08

    I came here looking for an answer for a similar question. I wanted to be able to extract the current class name from the java file being edited. I found a very neat way to do this in vim with an abbreviation:

    ab xclass =expand('%:t:r')
    

    Place this line in your .vimrc (or similar) for this to work. An abbreviation will auto-trigger as soon as you press space, and so I usually prefix them with 'x' to avoid their accidental expansion.

    The trick here is the combination of :t and :r in the argument to expand(). % is the "current file name", :t selects just the tail of the path ("last path component only") and :r selects just the root ("one extension removed"). (quoted parts are from the official expand() documentation.)

    So when you are creating a new class in file /a/b/ClassIAmAboutToCreate.java you would type:

    public class xclass {
    

    the moment you press space after "xclass", the abbreviation will be expanded to public class ClassIAmAboutToCreate, which is exactly what you need.

    Also, note that an abbreviation can be triggered by pressing Ctrl+] which avoids inserting a space after the class name.

提交回复
热议问题