diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..a1a212e
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,11 @@
+name: Bug Report
+description: Report a problem with pick-lsp-formatter
+labels: [bug]
+body:
+ - type: textarea
+ attributes:
+ label: "Description"
+ description: "Describe the problem you are reporting."
+ placeholder: "A clear and concise description of the bug"
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..eb17327
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,4 @@
+contact_links:
+ - name: Question
+ url: https://github.com/fmbarina/pick-lsp-formatter.nvim/discussions/new?category=q-a
+ about: Usage questions and support requests are answered in the discussions tab
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f2bd7c7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 Felipe Barina
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..4671a7a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,137 @@
+# plf.nvim
+
+**pick-lsp-formatter** is a plugin to choose a language server to format with.
+
+TODO: put a video of me using it here.
+
+## ✨ Features
+
+- 📝 Lets you pick a single language server when formatting
+- 💾 Remembers per filetype choices between sessions, which can be saved:
+ - per working directory
+ - per project
+
+By default, [`vim.buf.lsp.format()`](https://neovim.io/doc/user/lsp.html#vim.lsp.buf.format()) will format the buffer will all attached language servers capable of it, which is less than ideal. It *does* let you filter which language servers to use, but doing that every time isn't very nice. This is the issue this plugin aims to alleviate.
+
+It exists because I wanted to format lua using stylua, so I installed efm. I soon realized I didn't want *every* lua file formatted with stylua. Later, I even thought to stop using stylua at all—editorconfig is right there! Alas, pick-lsp-formatter already existed by then, so stylua gets another chance... in select environments.
+
+Anyways, hear me out... [efm](https://github.com/mattn/efm-langserver) + [configs](https://github.com/creativenull/efmls-configs-nvim) = good stuff.
+
+## 📦 Installation
+
+For the "I know what I'm doing" users:
+- `fmbarina/pick-lsp-formatter.nvim`
+- `require('plf').setup(opts)` if you need.
+- Install [telescope](https://github.com/nvim-telescope/telescope.nvim) or [dressing](https://github.com/stevearc/dressing.nvim) (or both) for a better picker.
+
+
+For lazy.nvim users
+
+ Add the following to your plugin list, your settings go in opts.
+
+ ```lua
+ {
+ 'fmbarina/pick-lsp-formatter.nvim',
+ dependencies = {
+ 'stevearc/dressing.nvim', -- Optional, better picker
+ 'nvim-telescope/telescope.nvim', -- Optional, better picker
+ },
+ main = 'plf',
+ lazy = true,
+ opts = {},
+ }
+ ```
+
+
+
+For packer.nvim users
+
+ Installation:
+
+ ```lua
+ use({
+ 'fmbarina/pick-lsp-formatter.nvim',
+ requires = {
+ 'stevearc/dressing.nvim', -- Optional, better picker
+ 'nvim-telescope/telescope.nvim', -- Optional, better picker
+ }
+ })
+ ```
+
+ Setup:
+
+ ```lua
+ require('plf').setup()
+ ```
+
+ Your settings can be passed through the setup function.
+
+
+Again, if you want a better picker (default kinda sucks), you only need to install one of the dependencies, but having both installed will work, too.
+
+## 💻️ Usage
+
+At least for now, pick-lsp-formatter won't create any commands, and it'll likely never create any keybindings.
+
+**Recommendation:** anywhere you `vim.lsp.buf.format()`'ed, use `require('plf').format()` instead. That's it.
+
+
+Example: my (simplified) lsp config
+
+ ```lua
+ lsp.on_attach(function(client, bufnr)
+ -- Stuff...
+ vim.keymap.set('n', 'lf', function()
+ -- vim.lsp.buf.format(opts) -- We take this out
+ require('plf').format(opts) -- And put this in
+ end, { buffer = bufnr, desc = 'LSP format buffer' })
+ -- More stuff...
+ end)
+ ```
+
+
+### API
+
+pick-lsp-formatter exposes a simple API to:
+
+- Automatically format with previously chosen server, or open picker to choose one.
+- Open picker with formatting capable servers and format buffer with chosen server.
+- Format with a specific server (*very* simple wrapper around `vim.lsp.buf.format`)
+
+For now, you can see these near the end of `lua/plf/init.lua`, but I'll document them properly soon™.
+
+## 🔧 Configuration
+
+The settings table (`opts`) may define the following fields.
+
+| Setting | Type | Description |
+|---------------|--------------------------------------|------------------------------------------------------------------------------|
+| data_dir | `string` | Path to store plugin data in. |
+| when_unset | `string`: `pick` or `fun(): boolean` | What to do when no server has been set as the formatter yet. See note below. |
+| set_on_pick | `boolean` | Whether to remember chosen server for this filetype. Note: see Scope below. |
+| find_project | `boolean` | Whether to save chosen servers for entire current project. |
+| find_patterns | `string[]` | Patterns to look for that define the root of a projet. |
+| exclude_lsp | `string[]` | Names of servers to never use for formatting. |
+
+Note that `when_unset` can be a function. When this is the case, it must return `true` to open picker or `false` to format normally.
+
+And "format normally" here meanss calling `vim.lsp.buf.format` as you would without this plugin.
+
+### Scope
+
+By default (when `find_project == false`) plf will save your choices for the current working directory. This may not be the best choice if your working directory rarely coincides with the root of projects you're working on. Worst case? You'll need pick servers again.
+
+If you would like to save your choices for the current project instead, use `find_project == true`. It'll then search upwards for files or directories in `find_patterns` and once it finds one, it will save your choices for that directory. It also falls back to the cwd if the root can't be found.
+
+### Default settings
+
+The plugin comes with the following defaults:
+
+```lua
+data_dir = vim.fn.expand(vim.fn.stdpath('state') .. '/picklspfmt/'),
+when_unset = 'pick',
+set_on_pick = true,
+find_project = false,
+find_patterns = { '.git/' },
+exclude_lsp = {},
+```
diff --git a/lua/plf/config.lua b/lua/plf/config.lua
new file mode 100644
index 0000000..a982276
--- /dev/null
+++ b/lua/plf/config.lua
@@ -0,0 +1,18 @@
+local M = {}
+
+local defaults = {
+ data_dir = vim.fn.expand(vim.fn.stdpath('state') .. '/picklspfmt/'),
+ when_unset = 'pick', -- nil, 'pick', fun()->bool
+ set_on_pick = true,
+ find_project = false,
+ find_patterns = { '.git/' },
+ exclude_lsp = {},
+}
+
+M.opts = {}
+
+function M.build(opts)
+ M.opts = vim.tbl_extend('force', {}, defaults, opts)
+end
+
+return M
diff --git a/lua/plf/init.lua b/lua/plf/init.lua
new file mode 100644
index 0000000..2eb0a8e
--- /dev/null
+++ b/lua/plf/init.lua
@@ -0,0 +1,222 @@
+local config = require('plf.config')
+
+local M = {}
+
+--- Get save file path for current working directory or project.
+---@return string #Path
+local function get_save_file()
+ local sep = '/'
+ if vim.fn.has('win32') == 1 then
+ sep = '[\\:]'
+ end
+
+ local current = vim.fn.getcwd()
+ if config.opts.find_project then
+ local files = vim.fs.find(config.opts.find_patterns, {
+ upward = true,
+ stop = vim.loop.os_homedir(),
+ path = vim.fs.dirname(vim.api.nvim_buf_get_name(0)),
+ limit = 1, -- default value, just to be explicit
+ })
+ if files[1] ~= nil then
+ current = vim.fs.dirname(files[1])
+ end
+ end
+
+ return config.opts.data_dir .. string.gsub(current, sep, '%%')
+end
+
+---@param fmt table filetype = server pairs
+---@return string #Serialized pairs
+local function serialize(fmt)
+ local ret = ''
+ for ft, server in pairs(fmt) do
+ ret = ret .. ft .. ' @uses ' .. server .. '\n'
+ end
+ return ret
+end
+
+---@param fmt string Serialized pairs
+---@return table #filetype = server pairs
+local function deserialize(fmt)
+ local ret = {}
+ for _, line in ipairs(vim.fn.split(fmt, '\n')) do
+ local pair = vim.fn.split(line, ' @uses ')
+ ret[pair[1]] = pair[2]
+ end
+ return ret
+end
+
+--- Save filetype = server pairs.
+---@param path string Path to save data in
+---@param fmt table filetype = server pairs to save
+local function save(path, fmt)
+ local handle = io.open(path, 'w+')
+ if handle then
+ handle:write(serialize(fmt))
+ handle:close()
+ end
+end
+
+--- Load filetype = server pairs.
+---@param path string Path to load data from
+---@return table #filetype = server pairs loaded
+local function load(path)
+ local fmt = {}
+
+ if vim.fn.filereadable(path) == 0 then
+ return fmt
+ end
+
+ local handle = io.open(path, 'r')
+ if handle then
+ fmt = deserialize(handle:read('*all'))
+ handle:close()
+ end
+
+ return fmt
+end
+
+--- Get active LSP servers capable of formatting.
+---@return table #Server list
+local function get_format_servers()
+ local bufnr = vim.api.nvim_get_current_buf()
+ local clients = vim.lsp.get_active_clients({ bufnr = bufnr })
+ local servers = {}
+
+ for i, client in ipairs(clients) do
+ if vim.tbl_contains(config.opts.exclude_lsp, client.name) then
+ table.remove(clients, i)
+ end
+ end
+
+ for _, client in ipairs(clients) do
+ if client.supports_method('textDocument/formatting') then
+ table.insert(servers, client.name)
+ end
+ end
+
+ return servers
+end
+
+--- Calls vim.lsp.buf.format with opts, extended with { name = server }.
+---@param opts table? Options passed to vim.lsp.buf.format()
+---@param server string Language server to format with
+function M.format_with(opts, server)
+ opts = vim.tbl_extend('force', {}, opts, { name = server })
+ vim.lsp.buf.format(opts)
+end
+
+--- Opens picker to choose LSP server for current filetype and formats buffer.
+--- Note that the buffer will only be formatted if an LSP server is picked.
+--- Picked server may be set as the default formatter for that filetype in the
+--- current working directory or project, following the `set_on_pick` setting.
+--- This behavior may be overridden using the set parameter.
+---@param opts table? Options passed to vim.lsp.buf.format()
+---@param set boolean? Override set_on_pick setting
+function M.pick_format(opts, set)
+ opts = opts or {}
+ if set == nil then
+ set = config.opts.set_on_pick
+ end
+
+ local ft = vim.bo.filetype
+ local servers = get_format_servers()
+ local server_count = vim.fn.len(servers)
+
+ if server_count == 1 then
+ M.format_with(opts, servers[1])
+ return
+ elseif server_count == 0 then
+ -- will fail, but we don't want plf to change *how* it fails (for now)
+ -- notifications, warnings, errors, etc. should stay the same with plf
+ vim.lsp.buf.format(opts)
+ return
+ end
+
+ local prompt = 'Format ' .. ft .. ' files with'
+ local function select(choice)
+ if set then
+ config.fmt[ft] = choice
+ end
+ M.format_with(opts, choice)
+ end
+
+ local has_telescope, _ = pcall(require, 'telescope')
+ if has_telescope then
+ -- I love telescope, but wow is this a lot of code for the
+ -- simplest picker I can think of (pick string of string[])
+ -- TODO: pretty sure this can be improved
+ local pickers = require('telescope.pickers')
+ local finders = require('telescope.finders')
+ local actions = require('telescope.actions')
+ local state = require('telescope.actions.state')
+ local conf = require('telescope.config').values
+ local theme = require('telescope.themes').get_dropdown()
+ pickers
+ .new(theme, {
+ prompt_title = prompt,
+ finder = finders.new_table({ results = servers }),
+ sorter = conf.generic_sorter(),
+ attach_mappings = function(prompt_bufnr, _)
+ actions.select_default:replace(function()
+ actions.close(prompt_bufnr)
+ local server = state.get_selected_entry()[1]
+ select(server)
+ end)
+ return true
+ end,
+ })
+ :find()
+ return
+ end
+
+ vim.ui.select(servers, {
+ prompt = prompt,
+ }, function(server)
+ if server ~= nil then
+ select(server)
+ end
+ end)
+end
+
+--- Formats buffer using selected LSP server for filetype.
+--- When no server is selected, `plf.pick_format()` will be called if:
+--- * `when_unset` == `pick` OR
+--- * `when_unset()` -> `true`
+---@param opts table? Options passed to vim.lsp.buf.format()
+function M.format(opts)
+ opts = opts or {}
+
+ local ft = vim.bo.filetype
+ local server = config.fmt[ft]
+ local behavior = config.opts.when_unset
+ local b_type = type(behavior)
+
+ if server ~= nil then
+ M.format_with(opts, server)
+ elseif (b_type == 'string') and (behavior == 'pick') then
+ M.pick_format()
+ elseif (b_type == 'function') and behavior() then
+ M.pick_format()
+ else
+ vim.lsp.buf.format(opts)
+ end
+end
+
+--- Setup plugin, must be called before `plf.format` and `plf.pick_format`.
+---@param opts table? Plugin options
+function M.setup(opts)
+ config.build(opts or {})
+ vim.fn.mkdir(config.opts.data_dir, 'p')
+ local save_file = get_save_file()
+ config.fmt = load(save_file)
+ vim.api.nvim_create_autocmd('VimLeavePre', {
+ group = vim.api.nvim_create_augroup('PickLspFormatter', {}),
+ callback = function()
+ save(save_file, config.fmt)
+ end,
+ })
+end
+
+return M