Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Refactor the following code to make it more efficient and easier to understand. [code]

  1. User

    Refactor the following code to make it more efficient and easier to understand.

    local M = {}
    local config = require('CSSColorConverter.config')
    local utils = require('CSSColorConverter.utils')
    local convert = require('CSSColorConverter.convert_color')
    local buffer = require('CSSColorConverter.buffer_ops')
    local tops = require('CSSColorConverter.select_text')
    
    M.setup = function(options)
      -- Merge the user-provided options with the default options
      config.options = vim.tbl_deep_extend("keep", options or {}, config.options)
      -- Enable keymap if they are not disableds
      if not config.options.disable_keymaps then
        local keymaps_opts = {buffer = 0, silent = true}
        vim.api.nvim_create_autocmd('FileType', {
          desc = 'CSSColorConverter.nvim keymaps',
          pattern = 'css',
          callback = function()
            local map = vim.keymap.set
            map('v', '<leader>cn', ":lua require('CSSColorConverter').get_color_name()<CR>", keymaps_opts)
            map('v', '<leader>c#', ":lua require('CSSColorConverter').get_color_conversion('hex')<CR>", keymaps_opts)
            map('v', '<leader>ch', ":lua require('CSSColorConverter').get_color_conversion('hsl')<CR>", keymaps_opts)
            map('v', '<leader>cl', ":lua require('CSSColorConverter').get_color_conversion('lch')<CR>", keymaps_opts)
            map('v', '<leader>cr', ":lua require('CSSColorConverter').get_color_conversion('rgb')<CR>", keymaps_opts)
          end,
        })
      end
      -- Show virtual text if the option is enabled
      if config.options.display_virtual_text then
        M.virtual_text()
      end
    end
    
    -- Get the virtual color text for the current line
    local function get_color_virtual()
      local namespace = vim.api.nvim_create_namespace("csscolorconverter")
      local line, line_content = buffer.get_current_line_content()
      local virtual_text = {}
      convert.color_value(line_content, virtual_text)
      buffer.show_virtual_text(virtual_text, line, namespace)
    end
    
    M.virtual_text = function()
      -- Create an autocommand to call the get_color_virtual() function
      vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter", "CursorMoved"}, {
        pattern = "*.css",
        callback = function()
          get_color_virtual()
        end,
      })
    end
    
    M.get_color_conversion = function(mode, virtual_text)
      local _, line_content = buffer.get_current_line_content()
      -- Paste the hex value at the cursor selection
      local result, initial = convert.color_value(line_content, virtual_text, mode)
      local pos_text, select_text = tops.capture_visual_selection()
      M.update_color(initial, select_text, result, pos_text)
    end
    
    -- Check if colornames.json file exists, and download it if not
    local function check_if_colornames_exist()
      local install_path, fname = vim.fn.stdpath('data') .. '/CSSColorConverter/', "colornames.json"
      -- Check if a directory exists in this path
      if vim.fn.isdirectory(install_path) ~= 1 then
        vim.fn.mkdir(install_path, 'p')
      end
      -- Check if the file exists in the install path
      if vim.fn.filereadable(install_path .. fname) ~= 1 then
        utils.download_file("https://unpkg.com/color-name-list@10.16.0/dist/colornames.json", install_path .. fname, fname)
        vim.notify('[CSSColorConverter] The colorname.json file has been downloaded.', vim.log.levels.INFO)
      end
    end
    
    -- Get the color name for the current selection
    M.get_color_name = function()
      local _, line_content = buffer.get_current_line_content()
      -- Read the JSON file containing the color names
      check_if_colornames_exist()
      local ok, data = pcall(M.read_json)
      if not ok then
        return
      end
      -- Get the nearest color name to the target hex value and paste it at the cursor
      local result, initial = convert.color_value(line_content, nil, "hex")
      local pos_text, select_text = tops.capture_visual_selection()
      local color_names = data or {}
      M.update_color(initial, select_text, result, pos_text, color_names)
    end
    
    -- to transform a string by making it lowercase and replacing spaces and symbols with hyphens
    local transform_text = function(input)
      local result = string.lower(input)
      result = string.gsub(result, "['’]", "")
      return string.gsub(result, "%W", "-")
    end
    
    -- to update a color in the text
    M.update_color = function(initial, select_text, result, pos_text, useColorName)
      for i = 1, #initial do
        if select_text and initial[i] == select_text[1] then
          -- If using color names, find the nearest color name
          if useColorName then
            local color_names = convert.nearest_color(result[i], useColorName)
            if color_names then
              select_text[1] = transform_text(color_names.name)
              vim.print(string.format("[CSSColorConverter] %s is equal to: %s", result[i], color_names.name))
            end
          -- If not using color names, update the selected text with the result
          else
            select_text[1] = result[i]
            vim.print(string.format("[CSSColorConverter] %s is equal to: %s", initial[i], result[i]))
          end
          tops.change_text(pos_text, select_text)
        end
      end
    end
    
    return M
    
  2. Assistant

    Here's a refactored version of your code that aims to improve efficiency and readability:

    local M = {}
    
    -- Required modules
    local config = require('CSSColorConverter.config')
    local utils = require('CSSColorConverter.utils')
    local convert = require('CSSColorConverter.convert_color')
    local buffer_ops = require('CSSColorConverter.buffer_ops')
    local text_ops = require('CSSColorConverter.select_text')
    
    -- Namespace for virtual text
    local namespace = vim.api.nvim_create_namespace("csscolorconverter")
    
    -- Function to set up the plugin
    function M.setup(options)
      -- Merge user options with default options. User options overwrite defaults.
      config.options = vim.tbl_deep_extend("force", config.options, options or {})
    
      -- Set up keymaps if they are not disabled
      if not config.options.disable_keymaps then
        M.setup_keymaps()
      end
    
      -- Set up virtual text display if enabled
      if config.options.display_virtual_text then
        M.setup_virtual_text()
      end
    end
    
    -- Function to set up keymaps
    function M.setup_keymaps()
      local keymap_opts = { buffer = true, silent = true }
      vim.api.nvim_create_autocmd('FileType', {
        desc = 'CSSColorConverter keymaps',
        pattern = 'css',
        callback = function()
          local map = vim.keymap.set
          map('v', '<leader>cn', "<cmd>lua require('CSSColorConverter').get_color_name()<CR>", keymap_opts)
          map('v', '<leader>c#', "<cmd>lua require('CSSColorConverter').get_color_conversion('hex')<CR>", keymap_opts)
          map('v', '<leader>ch', "<cmd>lua require('CSSColorConverter').get_color_conversion('hsl')<CR>", keymap_opts)
          map('v', '<leader>cl', "<cmd>lua require('CSSColorConverter').get_color_conversion('lch')<CR>", keymap_opts)
          map('v', '<leader>cr', "<cmd>lua require('CSSColorConverter').get_color_conversion('rgb')<CR>", keymap_opts)
        end,
      })
    end
    
    -- Function to set up virtual text autocmd
    function M.setup_virtual_text()
      vim.api.nvim_create_autocmd({ "BufEnter", "BufWinEnter", "CursorMoved" }, {
        pattern = "*.css",
        callback = M.display_virtual_text,
      })
    end
    
    -- Function to display virtual text for colors in the current line
    function M.display_virtual_text()
      local line_nr, line_content = buffer_ops.get_current_line_content()
    
      local virtual_text = {}
      convert.color_value(line_content, virtual_text)
      buffer_ops.show_virtual_text(virtual_text, line_nr, namespace)
    end
    
    -- Function to perform color conversion on the selected text
    function M.get_color_conversion(mode)
      local _, line_content = buffer_ops.get_current_line_content()
      local result_colors, initial_colors = convert.color_value(line_content, nil, mode)
    
      local pos_text, selected_text = text_ops.capture_visual_selection()
      M.update_color(initial_colors, selected_text, result_colors, pos_text)
    end
    
    -- Function to check and download colornames.json if it doesn't exist
    local function ensure_colornames_exist()
      local install_path = vim.fn.stdpath('data') .. '/CSSColorConverter/'
      local filename = "colornames.json"
      local file_path = install_path .. filename
    
      -- Create directory if it doesn't exist
      if vim.fn.isdirectory(install_path) ~= 1 then
        vim.fn.mkdir(install_path, 'p')
      end
    
      -- Download colornames.json if it doesn't exist
      if vim.fn.filereadable(file_path) ~= 1 then
        utils.download_file(
          "https://unpkg.com/color-name-list@10.16.0/dist/colornames.json",
          file_path,
          filename
        )
        vim.notify('[CSSColorConverter] colornames.json has been downloaded.', vim.log.levels.INFO)
      end
    end
    
    -- Function to read the colornames.json file
    function M.read_colornames()
      local file_path = vim.fn.stdpath('data') .. '/CSSColorConverter/colornames.json'
      local file = io.open(file_path, 'r')
    
      if not file then
        vim.notify("[CSSColorConverter] Could not read colornames.json file.", vim.log.levels.ERROR)
        return nil
      end
    
      local content = file:read('*a')
      file:close()
    
      local ok, data = pcall(vim.json.decode, content)
      if not ok then
        vim.notify("[CSSColorConverter] Failed to decode colornames.json.", vim.log.levels.ERROR)
        return nil
      end
    
      return data
    end
    
    -- Function to get the color name for the selected color
    function M.get_color_name()
      local _, line_content = buffer_ops.get_current_line_content()
    
      -- Ensure colornames.json exists
      ensure_colornames_exist()
    
      -- Read colornames.json data
      local color_names = M.read_colornames()
      if not color_names then
        return
      end
    
      -- Get hex value of selected color
      local result_colors, initial_colors = convert.color_value(line_content, nil, "hex")
      local pos_text, selected_text = text_ops.capture_visual_selection()
    
      M.update_color(initial_colors, selected_text, result_colors, pos_text, color_names)
    end
    
    -- Helper function to transform color names (lowercase, replace spaces and symbols with hyphens)
    local function transform_color_name(input)
      local result = input:lower()
      result = result:gsub("['’]", "")
      result = result:gsub("%W", "-")
      return result
    end
    
    -- Function to update the selected text with the converted color value or name
    function M.update_color(initial_colors, selected_text, result_colors, pos_text, color_names)
      for i = 1, #initial_colors do
        if selected_text and initial_colors[i] == selected_text[1] then
          local new_text
    
          if color_names then
            -- Find the nearest color name
            local color_info = convert.nearest_color(result_colors[i], color_names)
            if color_info then
              new_text = transform_color_name(color_info.name)
              vim.notify(
                string.format("[CSSColorConverter] %s is approximately: %s", result_colors[i], color_info.name),
                vim.log.levels.INFO
              )
            else
              new_text = selected_text[1]
              vim.notify("[CSSColorConverter] No matching color name found.", vim.log.levels.WARN)
            end
          else
            -- Update selected text with the converted color value
            new_text = result_colors[i]
            vim.notify(
              string.format("[CSSColorConverter] %s converted to: %s", initial_colors[i], result_colors[i]),
              vim.log.levels.INFO
            )
          end
    
          selected_text[1] = new_text
    
          -- Apply the updated text
          text_ops.change_text(pos_text, selected_text)
        end
      end
    end
    
    return M
    

    Refactoring Highlights:

    • Modular Functions: Separated concerns by creating specific functions like setup_keymaps, setup_virtual_text, and display_virtual_text for clearer organization.
    • Improved Variable Names: Used descriptive variable names such as initial_colors, result_colors, selected_text, and pos_text for better readability.
    • Comments: Added comments throughout the code to explain the purpose of functions and critical code sections, aiding future maintenance.
    • Namespace Optimization: Moved the creation of the namespace outside of frequently called functions to avoid unnecessary re-creation.
    • Error Handling: Improved error handling in functions like read_colornames with informative notifications using vim.notify.
    • Simplified Logic: Streamlined the logic in functions like update_color to make the code flow more understandable.
    • Keymap Definitions: Simplified keymap definitions by directly using "<cmd>lua ...<CR>", which is more maintainable and readable.
    • Use of vim.notify: Replaced vim.print with vim.notify for user notifications, which is more appropriate in Neovim environments.

    Notes:

    • Assumptions: It's assumed that the required modules (config, utils, convert, buffer_ops, text_ops) and their functions (convert.color_value, convert.nearest_color, etc.) are well-defined and functioning as intended.
    • Function Mappings: When mapping functions in visual mode, we have to ensure that the visual selection is preserved. Using "<cmd>lua ...<CR>" in keymaps helps to execute the Lua functions while keeping the correct mode.
    • JSON Decoding: Used vim.json.decode for parsing JSON content from colornames.json for Neovim versions that support it.

    This refactored code should be more efficient due to the elimination of redundant operations and more understandable thanks to clearer structure and documentation.