filetype.lua 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. if vim.g.did_load_filetypes then
  2. return
  3. end
  4. vim.g.did_load_filetypes = 1
  5. vim.api.nvim_create_augroup('filetypedetect', { clear = false })
  6. vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile', 'StdinReadPost' }, {
  7. group = 'filetypedetect',
  8. callback = function(args)
  9. if not vim.api.nvim_buf_is_valid(args.buf) then
  10. return
  11. end
  12. local ft, on_detect = vim.filetype.match({
  13. -- The unexpanded file name is needed here. #27914
  14. -- Neither args.file nor args.match are guaranteed to be unexpanded.
  15. filename = vim.fn.bufname(args.buf),
  16. buf = args.buf,
  17. })
  18. if not ft then
  19. -- Generic configuration file used as fallback
  20. ft = require('vim.filetype.detect').conf(args.file, args.buf)
  21. if ft then
  22. vim._with({ buf = args.buf }, function()
  23. vim.api.nvim_cmd({ cmd = 'setf', args = { 'FALLBACK', ft } }, {})
  24. end)
  25. end
  26. else
  27. -- on_detect is called before setting the filetype so that it can set any buffer local
  28. -- variables that may be used the filetype's ftplugin
  29. if on_detect then
  30. on_detect(args.buf)
  31. end
  32. vim._with({ buf = args.buf }, function()
  33. vim.api.nvim_cmd({ cmd = 'setf', args = { ft } }, {})
  34. end)
  35. end
  36. end,
  37. })
  38. -- Set up the autocmd for user scripts.vim
  39. vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile' }, {
  40. group = 'filetypedetect',
  41. command = "if !did_filetype() && expand('<amatch>') !~ g:ft_ignore_pat | runtime! scripts.vim | endif",
  42. })
  43. vim.api.nvim_create_autocmd('StdinReadPost', {
  44. group = 'filetypedetect',
  45. command = 'if !did_filetype() | runtime! scripts.vim | endif',
  46. })
  47. if not vim.g.ft_ignore_pat then
  48. vim.g.ft_ignore_pat = '\\.\\(Z\\|gz\\|bz2\\|zip\\|tgz\\)$'
  49. end
  50. -- These *must* be sourced after the autocommands above are created
  51. vim.cmd([[
  52. augroup filetypedetect
  53. runtime! ftdetect/*.{vim,lua}
  54. augroup END
  55. ]])