24

I'd like to get the current filetype as a variable in vimscript.

I'm making a function that grabs the current filetype and edits another file of corresponding filetype.

For example:

  • editing "foo/bar.txt", want to open "tmp/other.txt"
  • editing "foo/bar.cpp", want to open "tmp/other.cpp"

etc. I know that :set ft? displays the filetype in vim, but I'm not sure how to capture it and then open another file using it as part of the new file string.

aweg awef
  • 249
  • 1
  • 2
  • 3
  • 7
    `&filetype` does not necessarily correspond to the filename extension! Do you really want to use filetype for this, or would you rather parse the `bufname("%")` like `fnamemodify(bufname("%"), ":t")` to extract the current file's extension? For example, a file named 'foo.hpp' has a `&filetype` of cpp. Do you want to open "tmp/other.cpp" or "tmp/other.hpp" in this case? – cptstubing06 Feb 06 '13 at 05:24

2 Answers2

37

You can access the value of a setting by prefixing it with an ampersand. To assign the filetype to a variable, the following are equivalent:

let my_filetype = &filetype
let my_filetype = &ft

So for your example, assuming the filetype of the current buffer has been set, you could do something like

execute 'edit tmp/other.' . &filetype

Note that you need to execute the expression so that the variable is expanded before the strings are concatenated.

Prince Goulash
  • 15,295
  • 2
  • 46
  • 47
0

File type and file suffix are not necessarily the same thing. For example, if you are editing a .txt file, let zft = &ft sets zft to "text". let zfs = fnamemodify(bufname("%"), ":e") sets zfs to "txt".

trhodes
  • 1
  • 1