perf(filetype): skip contents check in match() if there is no contents (#29596)

Problem: `vim.filetype.match()` tries to match on contents even if there
  is no contents (empty buffer or `{''}` explicit contents).
  This results in extra avoidable execution duration for cases.
  It matters, for example, when trying to match filetype based solely
  on file name (which still needs `contents` or `buf` to properly match
  earlier in the code path).

Solution: skip matching based solely on contents if it is `{''}`. This
  works because:
    - Matching solely on content is done after any user-configured
      `vim.filetype.add()` hooks.
    - All default matching on content might depend on supplied path
      *only* if there is non-empty content (like in
      `require('vim.filetype.detect').match_from_hashbang()`).
This commit is contained in:
Evgeni Chasnovski 2024-07-08 19:20:32 +03:00 committed by GitHub
parent b3d94b1087
commit dc04ef2a20
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -2598,6 +2598,9 @@ function M.match(args)
contents = M._getlines(bufnr)
end
end
-- Match based solely on content only if there is any content (for performance)
if not (#contents == 1 and contents[1] == '') then
-- If name is nil, catch any errors from the contents filetype detection function.
-- If the function tries to use the filename that is nil then it will fail,
-- but this enables checks which do not need a filename to still work.
@ -2614,6 +2617,7 @@ function M.match(args)
return ft, on_detect
end
end
end
end
--- Get the default option value for a {filetype}.