Detecting when an option was never set by the user

I currently have a function like this in my Tree Sitter configuration, which gets called when setting up a buffer to use Tree Sitter:

function set_foldexpr()
  -- Apply 'foldexpr' only when the user hasn't set it otherwise.
  if vim.opt.foldmethod:get() == 'manual' then
    vim.opt_local.foldmethod = 'expr'
    vim.opt_local.foldexpr = 'nvim_treesitter#foldexpr()'
  end
end

This works well enough for me, because I personally never use manual folds, so foldmethod=manual might as well be “null” for my purposes.

But in general, is there a way to distinguish among these cases?

  1. The user has set an option in the current buffer, and it happens to be the same as the default value.
  2. The user has set an option globally, and it happens to be the same as the default value.
  3. The user has not set an option, so it is left at the default value.

In my opinion, it would be more “polite” to set foldmethod=expr only in cases 2 and 3, but not case 1.

1 Like

I would suggest using this to detect if it was set by a user:

vim.api.nvim_get_option_info('foldmethod').was_set