repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

neovim/lua/bugabinga/pivi/command.lua

Raw
local session = require 'bugabinga.pivi.session'
local help = require 'bugabinga.pivi.help'
local transcript = require 'bugabinga.pivi.transcript'
local context = require 'bugabinga.pivi.context'
local follow = require 'bugabinga.pivi.follow'
local publish = require 'bugabinga.pivi.publish'
local runtime = require 'bugabinga.pivi.runtime'
local comparison = require 'bugabinga.pivi.diff'

local INPUT_FILETYPE = 'pivi-input'

local notify = function( message, level )
  vim.notify( 'pivi: ' .. message, level or vim.log.levels.INFO )
end

--- Returns the active session, starting one when none exists.
--- A missing or unusable Pi is reported, never raised.
local require_session = function()
  local current = session.active()
  if current then return current end

  local available, failure = runtime.executable()
  if not available then
    notify( failure, vim.log.levels.ERROR )
    return nil
  end

  local ok, created = pcall( session.create, {} )
  if not ok then
    notify( 'cannot start pi: ' .. tostring( created ), vim.log.levels.ERROR )
    return nil
  end

  local started = created.client.failure()
  if started then
    notify( 'cannot start pi: ' .. started, vim.log.levels.ERROR )
    created.stop()
    return nil
  end

  return created
end

--- Decides whether `/` opens slash-command entry.
--- Only a pivi input buffer with the cursor on the first character qualifies.
--- @param bufnr number
--- @param col number zero based cursor column
local slash_opens_commands = function( bufnr, col )
  if not vim.api.nvim_buf_is_valid( bufnr ) then return false end
  if vim.bo[bufnr].filetype ~= INPUT_FILETYPE then return false end
  return col == 0
end

local fetch_commands = function( current, callback )
  current.request( { type = 'get_commands', }, function( response )
    local commands = {}
    if response.success and response.data then
      for _, entry in ipairs( response.data.commands or {} ) do
        table.insert( commands, entry )
      end
    end
    current.commands = commands
    if callback then callback( commands ) end
  end )
end

local run_slash_command = function( current, name, arguments )
  local message = '/' .. name
  if arguments and arguments ~= '' then message = message .. ' ' .. arguments end
  local accepted, rejection = current.submit( message, { capture = false, } )
  if not accepted then notify( rejection, vim.log.levels.WARN ) end
end

local pick_slash_command = function( current, on_pick )
  fetch_commands( current, function( commands )
    if #commands == 0 then
      notify( 'no pi commands available', vim.log.levels.WARN )
      return
    end
    vim.ui.select( commands, {
      prompt = 'pi command',
      format_item = function( entry )
        return '/' .. entry.name .. ( entry.description and ( '  ' .. entry.description ) or '' )
      end,
    }, function( choice )
      if not choice then return end
      on_pick( choice )
    end )
  end )
end

--- Opens a modifiable prompt buffer bound to a session.
local open_prompt = function( current )
  local bufnr = vim.api.nvim_create_buf( false, true )
  vim.bo[bufnr].buftype = 'nofile'
  vim.bo[bufnr].bufhidden = 'wipe'
  vim.bo[bufnr].filetype = INPUT_FILETYPE
  vim.b[bufnr].pivi_session = current.name
  pcall( vim.api.nvim_buf_set_name, bufnr, 'pivi://' .. current.name .. '/prompt' )

  vim.keymap.set( { 'n', 'i', }, '/', function()
    local col = vim.api.nvim_win_get_cursor( 0 )[2]
    if not slash_opens_commands( bufnr, col ) then return '/' end
    vim.schedule( function()
      pick_slash_command( current, function( choice )
        run_slash_command( current, choice.name, nil )
        transcript.show( current.buffer )
      end )
    end )
    return ''
  end, { buffer = bufnr, expr = true, desc = 'pivi slash command entry', } )

  vim.keymap.set( { 'n', 'i', }, '<c-s>', function()
    local lines = vim.api.nvim_buf_get_lines( bufnr, 0, -1, false )
    local text = vim.trim( table.concat( lines, '\n' ) )
    if text == '' then return end
    local accepted, rejection = current.submit( text, { capture = false, } )
    if not accepted then
      notify( rejection, vim.log.levels.WARN )
      return
    end
    vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { '', } )
    -- A submission the user cannot read the answer to is a dead end.
    transcript.show( current.buffer )
  end, { buffer = bufnr, desc = 'pivi submit prompt', } )

  if pcall( vim.cmd.split ) then
    local win = vim.api.nvim_get_current_win()
    vim.api.nvim_win_set_buf( win, bufnr )
    pcall( vim.api.nvim_win_set_height, win, 6 )
    transcript.decorate( win, current.name )
    vim.wo[win].winbar = '%#Title#π ' .. current.name ..
      '%*  %#Comment#<c-s> send  / commands%*'
    vim.cmd.startinsert()
  end
  return bufnr
end

local submit_text = function( text, options )
  local current = require_session()
  if not current then return false end

  local accepted, rejection = current.submit( text, options )
  if not accepted then
    notify( rejection, vim.log.levels.WARN )
    return false
  end
  transcript.show( current.buffer )
  return true
end

local subcommands = {}

subcommands.ask = function( arguments, modifiers )
  if arguments == '' then
    notify( 'ask needs a question', vim.log.levels.WARN )
    return
  end
  local options = {}
  if modifiers and modifiers.range and modifiers.range > 0 then
    options.snapshot = context.snapshot { range = {
      kind = 'range',
      first = { modifiers.line1, 0, },
      last = { modifiers.line2, 0, },
    }, }
  end
  submit_text( arguments, options )
end

subcommands.steer = function( arguments )
  submit_text( arguments, { delivery = 'steer', } )
end

subcommands['follow-up'] = function( arguments )
  submit_text( arguments, { delivery = 'follow_up', } )
end

subcommands.help = function( arguments )
  if arguments == '' then
    notify( 'help needs a question', vim.log.levels.WARN )
    return
  end
  help.ask( arguments )
end

subcommands.command = function( arguments )
  local current = require_session()
  if not current then return end

  local name, rest = arguments:match '^(%S+)%s*(.*)$'
  if name then
    run_slash_command( current, name, rest )
    transcript.show( current.buffer )
    return
  end
  pick_slash_command( current, function( choice )
    run_slash_command( current, choice.name, nil )
    transcript.show( current.buffer )
  end )
end

subcommands.start = function( arguments )
  local available, failure = runtime.executable()
  if not available then
    notify( failure, vim.log.levels.ERROR )
    return
  end

  local created = session.create { name = arguments ~= '' and arguments or nil, }
  publish.set_active( created.name )
  transcript.show( created.buffer )
  notify( 'session ' .. created.name )
end

subcommands.stop = function( arguments )
  local target = arguments ~= '' and session.get( arguments ) or session.active()
  if not target then
    notify( 'no session', vim.log.levels.WARN )
    return
  end
  target.stop()
  notify( 'stopped ' .. target.name )
end

subcommands.sessions = function()
  local names = session.list()
  if #names == 0 then
    notify( 'no sessions', vim.log.levels.WARN )
    return
  end
  vim.ui.select( names, { prompt = 'pi session', }, function( choice )
    if not choice then return end
    session.set_active( choice )
    local chosen = session.get( choice )
    if chosen then transcript.show( chosen.buffer ) end
  end )
end

subcommands.show = function()
  local current = session.active()
  if not current then
    notify( 'no session', vim.log.levels.WARN )
    return
  end
  transcript.show( current.buffer )
end

subcommands.prompt = function()
  local current = require_session()
  if not current then return end
  open_prompt( current )
end

subcommands.abort = function()
  local current = session.active()
  if not current then
    notify( 'no session', vim.log.levels.WARN )
    return
  end
  current.abort()
end

subcommands.queue = function()
  local current = session.active()
  if not current then
    notify( 'no session', vim.log.levels.WARN )
    return
  end
  local queue = current.status.queue or {}
  local entries = {}
  for _, item in ipairs( queue.steering or {} ) do table.insert( entries, 'steer: ' .. item ) end
  for _, item in ipairs( queue.follow_up or {} ) do table.insert( entries, 'follow-up: ' .. item ) end
  if #entries == 0 then
    notify 'queue is empty'
    return
  end
  notify( table.concat( entries, '\n' ) )
end

subcommands.clear = function()
  local current = session.active()
  if not current then
    notify( 'no session', vim.log.levels.WARN )
    return
  end
  current.clear_queue( function() notify 'queue cleared' end )
end

subcommands.diff = function()
  local bufnr = vim.api.nvim_get_current_buf()
  if vim.bo[bufnr].filetype ~= transcript.filetype then
    notify( 'move the cursor into a transcript first', vim.log.levels.WARN )
    return
  end

  local changed, _, faithful = comparison.open( bufnr )
  if not changed then
    notify( 'this entry reports no change to compare', vim.log.levels.WARN )
    return
  end
  if faithful == false then
    notify( 'the file has moved on since this change', vim.log.levels.WARN )
  end
end

subcommands.follow = function( arguments )
  follow.toggle( arguments ~= '' and arguments or nil )
  notify( 'follow ' .. ( follow.mode() or 'off' ) )
end

local names = function()
  local list = {}
  for key in pairs( subcommands ) do table.insert( list, key ) end
  table.sort( list )
  return list
end

local dispatch = function( options )
  local input = options.args or ''
  local name, rest = input:match '^(%S+)%s*(.*)$'
  if not name then
    subcommands.show()
    return
  end
  local handler = subcommands[name]
  if not handler then
    notify( 'unknown subcommand: ' .. name, vim.log.levels.ERROR )
    return
  end
  handler( rest or '', options )
end

local setup = function()
  vim.api.nvim_create_user_command( 'Pi', dispatch, {
    nargs = '*',
    range = true,
    desc = 'pivi native Pi integration',
    complete = function( lead, line )
      local before = line:match '^%s*Pi%s+(%S*)$'
      if before == nil then return {} end
      return vim.tbl_filter( function( candidate )
        return candidate:sub( 1, #lead ) == lead
      end, names() )
    end,
  } )

  vim.keymap.set( 'n', '<Plug>(pivi-show)', function() subcommands.show() end, { desc = 'pivi show transcript', } )
  vim.keymap.set( 'n', '<Plug>(pivi-prompt)', function() subcommands.prompt() end, { desc = 'pivi open prompt', } )
  vim.keymap.set( 'n', '<Plug>(pivi-abort)', function() subcommands.abort() end, { desc = 'pivi abort run', } )
  vim.keymap.set( 'n', '<Plug>(pivi-follow)', function() subcommands.follow '' end, { desc = 'pivi toggle follow', } )
end

return {
  input_filetype = INPUT_FILETYPE,
  setup = setup,
  dispatch = dispatch,
  subcommands = subcommands,
  names = names,
  slash_opens_commands = slash_opens_commands,
  open_prompt = open_prompt,
}