|
| 1 | +local telescope = require("telescope") |
| 2 | +local pickers = require("telescope.pickers") |
| 3 | +local finders = require("telescope.finders") |
| 4 | +local conf = require("telescope.config").values |
| 5 | +local actions = require("telescope.actions") |
| 6 | +local action_state = require("telescope.actions.state") |
| 7 | + |
| 8 | +local function session_exists(pterm, session_name) |
| 9 | + for _, name in ipairs(pterm.list()) do |
| 10 | + if name == session_name then |
| 11 | + return true |
| 12 | + end |
| 13 | + end |
| 14 | + return false |
| 15 | +end |
| 16 | + |
| 17 | +local function sessions(opts) |
| 18 | + opts = opts or {} |
| 19 | + |
| 20 | + local ok, pterm = pcall(require, "pterm") |
| 21 | + if not ok then |
| 22 | + vim.notify("Failed to load pterm module", vim.log.levels.ERROR) |
| 23 | + return |
| 24 | + end |
| 25 | + |
| 26 | + local session_names = pterm.list() |
| 27 | + if #session_names == 0 then |
| 28 | + vim.notify("No active pterm sessions", vim.log.levels.INFO) |
| 29 | + return |
| 30 | + end |
| 31 | + |
| 32 | + local entries = {} |
| 33 | + for _, name in ipairs(session_names) do |
| 34 | + local connected = pterm.connections[name] ~= nil |
| 35 | + table.insert(entries, { |
| 36 | + value = name, |
| 37 | + ordinal = name, |
| 38 | + display = connected and ("[connected] " .. name) or name, |
| 39 | + }) |
| 40 | + end |
| 41 | + |
| 42 | + pickers |
| 43 | + .new(opts, { |
| 44 | + prompt_title = "pterm sessions", |
| 45 | + finder = finders.new_table({ |
| 46 | + results = entries, |
| 47 | + entry_maker = function(entry) |
| 48 | + return { |
| 49 | + value = entry.value, |
| 50 | + ordinal = entry.ordinal, |
| 51 | + display = entry.display, |
| 52 | + } |
| 53 | + end, |
| 54 | + }), |
| 55 | + sorter = conf.generic_sorter(opts), |
| 56 | + attach_mappings = function(prompt_bufnr) |
| 57 | + actions.select_default:replace(function() |
| 58 | + actions.close(prompt_bufnr) |
| 59 | + |
| 60 | + local selection = action_state.get_selected_entry() |
| 61 | + if not selection or not selection.value then |
| 62 | + return |
| 63 | + end |
| 64 | + |
| 65 | + local session_name = selection.value |
| 66 | + if not session_exists(pterm, session_name) then |
| 67 | + vim.notify("Session '" .. session_name .. "' not found", vim.log.levels.ERROR) |
| 68 | + return |
| 69 | + end |
| 70 | + |
| 71 | + local open_ok, err = pcall(pterm.open, session_name) |
| 72 | + if not open_ok then |
| 73 | + vim.notify("Failed to open session '" .. session_name .. "': " .. tostring(err), vim.log.levels.ERROR) |
| 74 | + end |
| 75 | + end) |
| 76 | + return true |
| 77 | + end, |
| 78 | + }) |
| 79 | + :find() |
| 80 | +end |
| 81 | + |
| 82 | +return telescope.register_extension({ |
| 83 | + exports = { |
| 84 | + sessions = sessions, |
| 85 | + pterm = sessions, |
| 86 | + }, |
| 87 | +}) |
0 commit comments