Snippets

Sergio Luiz Araújo Silva toggle_boolean

Created by Sergio Araújo last modified
M.toggle_boolean_value_on_line = function()
  -- https://github.com/sagarrakshe/toggle-bool/blob/master/plugin/toggle_bool.py
  local values = {
    ["true"] = "false",
    ["false"] = "true",
    ["on"] = "off",
    ["off"] = "on",
    ["yes"] = "no",
    ["no"] = "yes",
    ["1"] = "0",
    ["0"] = "1",
    ["enable"] = "disable",
    ["disable"] = "enable",
    ["enabled"] = "disabled",
    ["disabled"] = "enabled",
    ["before"] = "after",
    ["after"] = "before",
    ["first"] = "last",
    ["last"] = "first",
    ["up"] = "down",
    ["down"] = "up",
  }

  local function toggle_bool_value(word)
    local toggleWord = values[word]
    if toggleWord == nil then
      -- Check if the word ends with a comma
      local wordWithoutComma = word:match("^(.-),$")
      if wordWithoutComma and values[wordWithoutComma] then
        return values[wordWithoutComma] .. ","
      end
      return word
    end
    return toggleWord
  end

  local current_line = vim.api.nvim_get_current_line()
  local indent = current_line:match("^%s*") -- Get the leading whitespace
  local line_words = {}
  local bool_count = 0

  for word in current_line:gmatch("[%w_'\"=]+[,]?") do
    if values[word] ~= nil or values[word:sub(1, -2)] ~= nil then
      bool_count = bool_count + 1
    end
    table.insert(line_words, word)
  end

  local cursor_word = vim.fn.expand("<cword>")

  if bool_count == 1 then
    for i, word in ipairs(line_words) do
      if values[word] ~= nil or values[word:sub(1, -2)] ~= nil or word:match("^.+,$") then
        line_words[i] = toggle_bool_value(word)
      end
    end
  else
    for i, word in ipairs(line_words) do
      if word == cursor_word or word:match("^.+,$") then
        line_words[i] = toggle_bool_value(word)
        break
      end
    end
  end

  local new_line = indent .. table.concat(line_words, " ")
  vim.api.nvim_set_current_line(new_line)
end

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.