{-# LANGUAGE InstanceSigs        #-}
{-# LANGUAGE LambdaCase          #-}
{-# LANGUAGE NamedFieldPuns      #-}
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  XMonad.Util.Run
-- Description :  Several commands, as well as an EDSL, to run external processes.
-- Copyright   :  (C) 2007  Spencer Janssen, Andrea Rossato, glasser@mit.edu
--                    2022  Tony Zorman
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Tony Zorman <soliditsallgood@mailbox.org>
-- Stability   :  unstable
-- Portability :  unportable
--
-- This module provides several commands to run an external process.
-- Additionally, it provides an abstraction—particularly geared towards
-- programs like terminals or Emacs—to specify these processes from
-- XMonad in a compositional way.
--
-- Originally, this module was composed of functions formerly defined in
-- "XMonad.Util.Dmenu" (by Spencer Janssen), "XMonad.Util.Dzen" (by
-- glasser\@mit.edu) and @XMonad.Util.RunInXTerm@ (by Andrea Rossato).
-----------------------------------------------------------------------------

module XMonad.Util.Run (
  -- * Usage
  -- $usage
  runProcessWithInput,
  runProcessWithInputAndWait,
  safeSpawn,
  safeSpawnProg,
  unsafeSpawn,
  runInTerm,
  safeRunInTerm,
  seconds,
  spawnPipe,
  spawnPipeWithLocaleEncoding,
  spawnPipeWithUtf8Encoding,
  spawnPipeWithNoEncoding,

  -- * Compositionally Spawning Processes #EDSL#
  -- $EDSL

  -- ** Configuration and Running
  ProcessConfig (..),
  Input,
  spawnExternalProcess,
  proc,
  getInput,

  -- ** Programs
  inEditor,
  inTerm,
  termInDir,
  inProgram,

  -- ** General Combinators
  (>->),
  (>-$),
  inWorkingDir,
  execute,
  eval,
  setXClass,
  asString,

  -- ** Emacs Integration
  EmacsLib (..),
  setFrameName,
  withEmacsLibs,
  inEmacs,
  elispFun,
  asBatch,
  require,
  progn,
  quote,

  -- * Re-exports
  hPutStr,
  hPutStrLn,
) where

import XMonad
import XMonad.Prelude
import qualified XMonad.Util.ExtensibleConf as XC

import Codec.Binary.UTF8.String (encodeString)
import Control.Concurrent (threadDelay)
import System.Directory (getDirectoryContents)
import System.IO
import System.Posix.IO
import System.Posix.Process (createSession, executeFile, forkProcess)
import System.Process (runInteractiveProcess)

{- $usage

You can use this module by importing it in your @xmonad.hs@

> import XMonad.Util.Run

It then all depends on what you want to do:

  - If you want to compositionally spawn programs, see [the relevant
    extended documentation](#g:EDSL).

  - For an example usage of 'runInTerm' see "XMonad.Prompt.Ssh".

  - For an example usage of 'runProcessWithInput' see
    "XMonad.Prompt.DirectoryPrompt", "XMonad.Util.Dmenu",
    "XMonad.Prompt.ShellPrompt", "XMonad.Actions.WmiiActions", or
    "XMonad.Prompt.WorkspaceDir".

  - For an example usage of 'runProcessWithInputAndWait' see
    "XMonad.Util.Dzen".
-}

-- | Returns the output.
runProcessWithInput :: MonadIO m => FilePath -> [String] -> String -> m String
runProcessWithInput :: FilePath -> [FilePath] -> FilePath -> m FilePath
runProcessWithInput FilePath
cmd [FilePath]
args FilePath
input = IO FilePath -> m FilePath
forall (m :: * -> *) a. MonadIO m => IO a -> m a
io (IO FilePath -> m FilePath) -> IO FilePath -> m FilePath
forall a b. (a -> b) -> a -> b
$ do
    (Handle
pin, Handle
pout, Handle
perr, ProcessHandle
_) <- FilePath
-> [FilePath]
-> Maybe FilePath
-> Maybe [(FilePath, FilePath)]
-> IO (Handle, Handle, Handle, ProcessHandle)
runInteractiveProcess (FilePath -> FilePath
encodeString FilePath
cmd)
                                            ((FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map FilePath -> FilePath
encodeString [FilePath]
args) Maybe FilePath
forall a. Maybe a
Nothing Maybe [(FilePath, FilePath)]
forall a. Maybe a
Nothing
    Handle -> FilePath -> IO ()
hPutStr Handle
pin FilePath
input
    Handle -> IO ()
hClose Handle
pin
    FilePath
output <- Handle -> IO FilePath
hGetContents Handle
pout
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (FilePath
output FilePath -> FilePath -> Bool
forall a. Eq a => a -> a -> Bool
== FilePath
output) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    Handle -> IO ()
hClose Handle
pout
    Handle -> IO ()
hClose Handle
perr
    -- no need to waitForProcess, we ignore SIGCHLD
    FilePath -> IO FilePath
forall (m :: * -> *) a. Monad m => a -> m a
return FilePath
output

-- | Wait is in &#956; (microseconds)
runProcessWithInputAndWait :: MonadIO m => FilePath -> [String] -> String -> Int -> m ()
runProcessWithInputAndWait :: FilePath -> [FilePath] -> FilePath -> Int -> m ()
runProcessWithInputAndWait FilePath
cmd [FilePath]
args FilePath
input Int
timeout = IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
io (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ do
    ProcessID
_ <- IO () -> IO ProcessID
forall (m :: * -> *). MonadIO m => IO () -> m ProcessID
xfork (IO () -> IO ProcessID) -> IO () -> IO ProcessID
forall a b. (a -> b) -> a -> b
$ do
        (Handle
pin, Handle
pout, Handle
perr, ProcessHandle
_) <- FilePath
-> [FilePath]
-> Maybe FilePath
-> Maybe [(FilePath, FilePath)]
-> IO (Handle, Handle, Handle, ProcessHandle)
runInteractiveProcess (FilePath -> FilePath
encodeString FilePath
cmd)
                                            ((FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map FilePath -> FilePath
encodeString [FilePath]
args) Maybe FilePath
forall a. Maybe a
Nothing Maybe [(FilePath, FilePath)]
forall a. Maybe a
Nothing
        Handle -> FilePath -> IO ()
hPutStr Handle
pin FilePath
input
        Handle -> IO ()
hFlush Handle
pin
        Int -> IO ()
threadDelay Int
timeout
        Handle -> IO ()
hClose Handle
pin
        Handle -> IO ()
hClose Handle
pout
        Handle -> IO ()
hClose Handle
perr
        -- no need to waitForProcess, we ignore SIGCHLD
        () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Multiplies by ONE MILLION, for functions that take microseconds.
--
-- Use like:
--
-- > (5.5 `seconds`)
--
-- In GHC 7 and later, you must either enable the PostfixOperators extension
-- (by adding
--
-- > {-# LANGUAGE PostfixOperators #-}
--
-- to the top of your file) or use seconds in prefix form:
--
-- > seconds 5.5
seconds :: Rational -> Int
seconds :: Rational -> Int
seconds = Rational -> Int
forall a. Enum a => a -> Int
fromEnum (Rational -> Int) -> (Rational -> Rational) -> Rational -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
* Rational
1000000)

{- | 'safeSpawn' bypasses 'spawn', because spawn passes
strings to \/bin\/sh to be interpreted as shell commands. This is
often what one wants, but in many cases the passed string will contain
shell metacharacters which one does not want interpreted as such (URLs
particularly often have shell metacharacters like \'&\' in them). In
this case, it is more useful to specify a file or program to be run
and a string to give it as an argument so as to bypass the shell and
be certain the program will receive the string as you typed it.

Examples:

> , ((modm, xK_Print), unsafeSpawn "import -window root $HOME/xwd-$(date +%s)$$.png")
> , ((modm, xK_d    ), safeSpawn "firefox" [])

Note that the unsafeSpawn example must be unsafe and not safe because
it makes use of shell interpretation by relying on @$HOME@ and
interpolation, whereas the safeSpawn example can be safe because
Firefox doesn't need any arguments if it is just being started. -}
safeSpawn :: MonadIO m => FilePath -> [String] -> m ()
safeSpawn :: FilePath -> [FilePath] -> m ()
safeSpawn FilePath
prog [FilePath]
args = IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
io (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ IO ProcessID -> IO ()
forall a. IO a -> IO ()
void_ (IO ProcessID -> IO ()) -> IO ProcessID -> IO ()
forall a b. (a -> b) -> a -> b
$ IO () -> IO ProcessID
forkProcess (IO () -> IO ProcessID) -> IO () -> IO ProcessID
forall a b. (a -> b) -> a -> b
$ do
  IO ()
forall (m :: * -> *). MonadIO m => m ()
uninstallSignalHandlers
  ProcessID
_ <- IO ProcessID
createSession
  FilePath
-> Bool -> [FilePath] -> Maybe [(FilePath, FilePath)] -> IO ()
forall a.
FilePath
-> Bool -> [FilePath] -> Maybe [(FilePath, FilePath)] -> IO a
executeFile (FilePath -> FilePath
encodeString FilePath
prog) Bool
True ((FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map FilePath -> FilePath
encodeString [FilePath]
args) Maybe [(FilePath, FilePath)]
forall a. Maybe a
Nothing
    where void_ :: IO a -> IO ()
void_ = (IO a -> IO () -> IO ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()) -- TODO: replace with Control.Monad.void / void not in ghc6 apparently

-- | Simplified 'safeSpawn'; only takes a program (and no arguments):
--
-- > , ((modm, xK_d    ), safeSpawnProg "firefox")
safeSpawnProg :: MonadIO m => FilePath -> m ()
safeSpawnProg :: FilePath -> m ()
safeSpawnProg = (FilePath -> [FilePath] -> m ()) -> [FilePath] -> FilePath -> m ()
forall a b c. (a -> b -> c) -> b -> a -> c
flip FilePath -> [FilePath] -> m ()
forall (m :: * -> *). MonadIO m => FilePath -> [FilePath] -> m ()
safeSpawn []

-- | An alias for 'spawn'; the name emphasizes that one is calling out to a
--   Turing-complete interpreter which may do things one dislikes; for details, see 'safeSpawn'.
unsafeSpawn :: MonadIO m => String -> m ()
unsafeSpawn :: FilePath -> m ()
unsafeSpawn = FilePath -> m ()
forall (m :: * -> *). MonadIO m => FilePath -> m ()
spawn

-- | Open a terminal emulator. The terminal emulator is specified in the default configuration as xterm by default. It is then
-- asked to pass the shell a command with certain options. This is unsafe in the sense of 'unsafeSpawn'
unsafeRunInTerm, runInTerm :: String -> String -> X ()
unsafeRunInTerm :: FilePath -> FilePath -> X ()
unsafeRunInTerm FilePath
options FilePath
command = (XConf -> FilePath) -> X FilePath
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks (XConfig Layout -> FilePath
forall (l :: * -> *). XConfig l -> FilePath
terminal (XConfig Layout -> FilePath)
-> (XConf -> XConfig Layout) -> XConf -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. XConf -> XConfig Layout
config) X FilePath -> (FilePath -> X ()) -> X ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \FilePath
t -> FilePath -> X ()
forall (m :: * -> *). MonadIO m => FilePath -> m ()
unsafeSpawn (FilePath -> X ()) -> FilePath -> X ()
forall a b. (a -> b) -> a -> b
$ FilePath
t FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
" " FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
options FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
" -e " FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
command
runInTerm :: FilePath -> FilePath -> X ()
runInTerm = FilePath -> FilePath -> X ()
unsafeRunInTerm

-- | Run a given program in the preferred terminal emulator; see 'runInTerm'. This makes use of 'safeSpawn'.
safeRunInTerm :: String -> String -> X ()
safeRunInTerm :: FilePath -> FilePath -> X ()
safeRunInTerm FilePath
options FilePath
command = (XConf -> FilePath) -> X FilePath
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks (XConfig Layout -> FilePath
forall (l :: * -> *). XConfig l -> FilePath
terminal (XConfig Layout -> FilePath)
-> (XConf -> XConfig Layout) -> XConf -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. XConf -> XConfig Layout
config) X FilePath -> (FilePath -> X ()) -> X ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \FilePath
t -> FilePath -> [FilePath] -> X ()
forall (m :: * -> *). MonadIO m => FilePath -> [FilePath] -> m ()
safeSpawn FilePath
t [FilePath
options, FilePath
" -e " FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
command]

-- | Launch an external application through the system shell and
-- return a 'Handle' to its standard input. Note that the 'Handle'
-- is a text 'Handle' using the current locale encoding.
spawnPipe :: MonadIO m => String -> m Handle
spawnPipe :: FilePath -> m Handle
spawnPipe = FilePath -> m Handle
forall (m :: * -> *). MonadIO m => FilePath -> m Handle
spawnPipeWithLocaleEncoding

-- | Same as 'spawnPipe'.
spawnPipeWithLocaleEncoding :: MonadIO m => String -> m Handle
spawnPipeWithLocaleEncoding :: FilePath -> m Handle
spawnPipeWithLocaleEncoding = TextEncoding -> FilePath -> m Handle
forall (m :: * -> *).
MonadIO m =>
TextEncoding -> FilePath -> m Handle
spawnPipe' TextEncoding
localeEncoding

-- | Same as 'spawnPipe', but forces the UTF-8 encoding regardless of locale.
spawnPipeWithUtf8Encoding :: MonadIO m => String -> m Handle
spawnPipeWithUtf8Encoding :: FilePath -> m Handle
spawnPipeWithUtf8Encoding = TextEncoding -> FilePath -> m Handle
forall (m :: * -> *).
MonadIO m =>
TextEncoding -> FilePath -> m Handle
spawnPipe' TextEncoding
utf8

-- | Same as 'spawnPipe', but forces the 'char8' encoding, so unicode strings
-- need 'Codec.Binary.UTF8.String.encodeString'. Should never be needed, but
-- some X functions return already encoded Strings, so it may possibly be
-- useful for someone.
spawnPipeWithNoEncoding :: MonadIO m => String -> m Handle
spawnPipeWithNoEncoding :: FilePath -> m Handle
spawnPipeWithNoEncoding = TextEncoding -> FilePath -> m Handle
forall (m :: * -> *).
MonadIO m =>
TextEncoding -> FilePath -> m Handle
spawnPipe' TextEncoding
char8

spawnPipe' :: MonadIO m => TextEncoding -> String -> m Handle
spawnPipe' :: TextEncoding -> FilePath -> m Handle
spawnPipe' TextEncoding
encoding FilePath
x = IO Handle -> m Handle
forall (m :: * -> *) a. MonadIO m => IO a -> m a
io (IO Handle -> m Handle) -> IO Handle -> m Handle
forall a b. (a -> b) -> a -> b
$ do
    (Fd
rd, Fd
wr) <- IO (Fd, Fd)
createPipe
    Fd -> FdOption -> Bool -> IO ()
setFdOption Fd
wr FdOption
CloseOnExec Bool
True
    Handle
h <- Fd -> IO Handle
fdToHandle Fd
wr
    Handle -> TextEncoding -> IO ()
hSetEncoding Handle
h TextEncoding
encoding
    Handle -> BufferMode -> IO ()
hSetBuffering Handle
h BufferMode
LineBuffering
    ProcessID
_ <- IO () -> IO ProcessID
forall (m :: * -> *). MonadIO m => IO () -> m ProcessID
xfork (IO () -> IO ProcessID) -> IO () -> IO ProcessID
forall a b. (a -> b) -> a -> b
$ do
          Fd
_ <- Fd -> Fd -> IO Fd
dupTo Fd
rd Fd
stdInput
          FilePath
-> Bool -> [FilePath] -> Maybe [(FilePath, FilePath)] -> IO ()
forall a.
FilePath
-> Bool -> [FilePath] -> Maybe [(FilePath, FilePath)] -> IO a
executeFile FilePath
"/bin/sh" Bool
False [FilePath
"-c", FilePath -> FilePath
encodeString FilePath
x] Maybe [(FilePath, FilePath)]
forall a. Maybe a
Nothing
    Fd -> IO ()
closeFd Fd
rd
    Handle -> IO Handle
forall (m :: * -> *) a. Monad m => a -> m a
return Handle
h

{- $EDSL

To use the provided EDSL, you must first add the 'spawnExternalProcess'
combinator to your xmonad configuration, like so:

> main = xmonad $ … $ spawnExternalProcess def $ … $ def

See 'ProcessConfig' for a list of all default configuration options, in
case you'd like to change them—especially if you want to make use of the
Emacs integration.

After that, the real fun begins!  The format for spawning these
processes is always the same: a call to 'proc', its argument being a
bunch of function calls, separated by the pipe operator '(>->)'.  You
can just bind the resulting function to a key; no additional plumbing
required.  For example, using "XMonad.Util.EZConfig" syntax and with
@terminal = "alacritty"@ in you XMonad configuration, spawning a @ghci@
session with a special class name, "calculator", would look like

> ("M-y", proc $ inTerm >-> setXClass "calculator" >-> execute "ghci")

which would translate, more or less, to @\/usr\/bin\/sh -c "alacritty
--class calculator -e ghci"@.  The usefulness of this notation becomes
apparent with more complicated examples:

> proc $ inEmacs
>    >-> withEmacsLibs [OwnFile "mailboxes"]
>    >-> execute (elispFun "notmuch")
>    >-> setFrameName "mail"

This is equivalent to spawning

> emacs -l /home/slot/.config/emacs/lisp/mailboxes.el
>       -e '(notmuch)'
>       -F '(quote (name . "mail"))'

Notice how we did not have to specify the whole path to @mailboxes.el@,
since we had set the correct 'emacsLispDir' upon starting xmonad.  This
becomes especially relevant when running Emacs in batch mode, where one
has to include [M,Non-GNU]ELPA packages in the call, whose exact names
may change at any time.  Then the following

> do url <- getSelection  -- from XMonad.Util.XSelection
>    proc $ inEmacs
>       >-> withEmacsLibs [ElpaLib "dash", ElpaLib "s", OwnFile "arXiv-citation"]
>       >-> asBatch
>       >-> execute (elispFun $ "arXiv-citation" <> asString url)

becomes

> emacs -L /home/slot/.config/emacs/elpa/dash-20220417.2250
>       -L /home/slot/.config/emacs/elpa/s-20210616.619
>       -l /home/slot/.config/emacs/lisp/arXiv-citation.el
>       --batch
>       -e '(arXiv-citation "<url-in-the-primary-selection>")'

which would be quite bothersome to type indeed!

-}

-----------------------------------------------------------------------
-- Types and whatnot

-- | Additional information that might be useful when spawning external
-- programs.
data ProcessConfig = ProcessConfig
  { ProcessConfig -> FilePath
editor :: !String
    -- ^ Default editor.  Defaults to @"emacsclient -c -a ''"@.
  , ProcessConfig -> FilePath
emacsLispDir :: !FilePath
    -- ^ Directory for your custom Emacs lisp files.  Probably
    -- @user-emacs-directory@ or @user-emacs-directory/lisp@.  Defaults
    -- to @"~\/.config\/emacs\/lisp\/"@
  , ProcessConfig -> FilePath
emacsElpaDir :: !FilePath
    -- ^ Directory for all packages from [M,Non-GNU]ELPA; probably
    -- @user-emacs-directory/elpa@.  Defaults to
    -- @"~\/.config\/emacs\/elpa"@.
  , ProcessConfig -> FilePath
emacs :: !String
    -- ^ /Standalone/ Emacs executable; this should not be @emacsclient@
    -- since, for example, the client does not support @--batch@ mode.
    -- Defaults to @"emacs"@.
  }

-- | Given a 'ProcessConfig', remember it for spawning external
-- processes later on.
spawnExternalProcess :: ProcessConfig -> XConfig l -> XConfig l
spawnExternalProcess :: ProcessConfig -> XConfig l -> XConfig l
spawnExternalProcess = (ProcessConfig -> ProcessConfig) -> XConfig l -> XConfig l
forall a (l :: * -> *).
(Default a, Typeable a) =>
(a -> a) -> XConfig l -> XConfig l
XC.modifyDef ((ProcessConfig -> ProcessConfig) -> XConfig l -> XConfig l)
-> (ProcessConfig -> ProcessConfig -> ProcessConfig)
-> ProcessConfig
-> XConfig l
-> XConfig l
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ProcessConfig -> ProcessConfig -> ProcessConfig
forall a b. a -> b -> a
const

instance Default ProcessConfig where
  def :: ProcessConfig
  def :: ProcessConfig
def = ProcessConfig :: FilePath -> FilePath -> FilePath -> FilePath -> ProcessConfig
ProcessConfig
    { editor :: FilePath
editor       = FilePath
"emacsclient -c -a ''"
    , emacsLispDir :: FilePath
emacsLispDir = FilePath
"~/.config/emacs/lisp/"
    , emacsElpaDir :: FilePath
emacsElpaDir = FilePath
"~/.config/emacs/elpa/"
    , emacs :: FilePath
emacs        = FilePath
"emacs"
    }

-- | Convenient type alias.
type Input = ShowS

-----------------------------------------------------------------------
-- Combinators

-- | Combine inputs together.
(>->) :: X Input -> X Input -> X Input
>-> :: X (FilePath -> FilePath)
-> X (FilePath -> FilePath) -> X (FilePath -> FilePath)
(>->) = X (FilePath -> FilePath)
-> X (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall a. Semigroup a => a -> a -> a
(<>)
infixr 3 >->

-- | Combine an input with an ordinary string.
(>-$) :: X Input -> X String -> X Input
>-$ :: X (FilePath -> FilePath) -> X FilePath -> X (FilePath -> FilePath)
(>-$) X (FilePath -> FilePath)
xi X FilePath
xs = X (FilePath -> FilePath)
xi X (FilePath -> FilePath)
-> X (FilePath -> FilePath) -> X (FilePath -> FilePath)
>-> (FilePath -> FilePath -> FilePath)
-> X FilePath -> X (FilePath -> FilePath)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap FilePath -> FilePath -> FilePath
mkDList X FilePath
xs
infixr 3 >-$

-- | Spawn a completed input.
proc :: X Input -> X ()
proc :: X (FilePath -> FilePath) -> X ()
proc X (FilePath -> FilePath)
xi = FilePath -> X ()
forall (m :: * -> *). MonadIO m => FilePath -> m ()
spawn (FilePath -> X ()) -> X FilePath -> X ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< X (FilePath -> FilePath) -> X FilePath
getInput X (FilePath -> FilePath)
xi

-- | Get the completed input string.
getInput :: X Input -> X String
getInput :: X (FilePath -> FilePath) -> X FilePath
getInput X (FilePath -> FilePath)
xi = X (FilePath -> FilePath)
xi X (FilePath -> FilePath)
-> ((FilePath -> FilePath) -> FilePath) -> X FilePath
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> ((FilePath -> FilePath) -> FilePath -> FilePath
forall a b. (a -> b) -> a -> b
$ FilePath
"")

-- | Use the 'editor'.
inEditor :: X Input
inEditor :: X (FilePath -> FilePath)
inEditor = (ProcessConfig -> X (FilePath -> FilePath))
-> X (FilePath -> FilePath)
forall (m :: * -> *) a b.
(MonadReader XConf m, Typeable a, Default a) =>
(a -> m b) -> m b
XC.withDef ((ProcessConfig -> X (FilePath -> FilePath))
 -> X (FilePath -> FilePath))
-> (ProcessConfig -> X (FilePath -> FilePath))
-> X (FilePath -> FilePath)
forall a b. (a -> b) -> a -> b
$ \ProcessConfig{FilePath
editor :: FilePath
editor :: ProcessConfig -> FilePath
editor} -> (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath -> FilePath) -> X (FilePath -> FilePath))
-> (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall a b. (a -> b) -> a -> b
$ FilePath -> FilePath -> FilePath
mkDList FilePath
editor

-- | Use the 'XMonad.Core.XConfig.terminal'.
inTerm :: X Input
inTerm :: X (FilePath -> FilePath)
inTerm = (XConf -> FilePath -> FilePath) -> X (FilePath -> FilePath)
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks ((XConf -> FilePath -> FilePath) -> X (FilePath -> FilePath))
-> (XConf -> FilePath -> FilePath) -> X (FilePath -> FilePath)
forall a b. (a -> b) -> a -> b
$ FilePath -> FilePath -> FilePath
mkDList (FilePath -> FilePath -> FilePath)
-> (XConf -> FilePath) -> XConf -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. XConfig Layout -> FilePath
forall (l :: * -> *). XConfig l -> FilePath
terminal (XConfig Layout -> FilePath)
-> (XConf -> XConfig Layout) -> XConf -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. XConf -> XConfig Layout
config

-- | Execute the argument.  Current /thing/ must support a @-e@ option.
-- For programs such as Emacs, 'eval' may be the safer option; while
-- @emacsclient@ supports @-e@, the @emacs@ executable itself does not.
execute :: String -> X Input
execute :: FilePath -> X (FilePath -> FilePath)
execute FilePath
this = (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath
" -e " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
this) FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)

-- | Eval(uate) the argument.  Current /thing/ must support a @--eval@
-- option.
eval :: String -> X Input
eval :: FilePath -> X (FilePath -> FilePath)
eval FilePath
this = (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath
" --eval " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
this) FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)

-- | Use 'emacs'.
inEmacs :: X Input
inEmacs :: X (FilePath -> FilePath)
inEmacs = (ProcessConfig -> X (FilePath -> FilePath))
-> X (FilePath -> FilePath)
forall (m :: * -> *) a b.
(MonadReader XConf m, Typeable a, Default a) =>
(a -> m b) -> m b
XC.withDef ((ProcessConfig -> X (FilePath -> FilePath))
 -> X (FilePath -> FilePath))
-> (ProcessConfig -> X (FilePath -> FilePath))
-> X (FilePath -> FilePath)
forall a b. (a -> b) -> a -> b
$ \ProcessConfig{FilePath
emacs :: FilePath
emacs :: ProcessConfig -> FilePath
emacs} -> (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath -> FilePath) -> X (FilePath -> FilePath))
-> (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall a b. (a -> b) -> a -> b
$ FilePath -> FilePath -> FilePath
mkDList FilePath
emacs

-- | Use the given program.
inProgram :: String -> X Input
inProgram :: FilePath -> X (FilePath -> FilePath)
inProgram = (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath -> FilePath) -> X (FilePath -> FilePath))
-> (FilePath -> FilePath -> FilePath)
-> FilePath
-> X (FilePath -> FilePath)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> FilePath -> FilePath
mkDList

-- | Spawn /thing/ in the current working directory.  /thing/ must
-- support a @--working-directory@ option.
inWorkingDir :: X Input
inWorkingDir :: X (FilePath -> FilePath)
inWorkingDir = (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FilePath
" --working-directory " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)

-- | Set a frame name for the @emacsclient@.
--
-- Note that this uses the @-F@ option to set the
-- <https://www.gnu.org/software/emacs/manual/html_node/emacs/Frame-Parameters.html frame parameters>
-- alist, which the @emacs@ executable does not support.
setFrameName :: String -> X Input
setFrameName :: FilePath -> X (FilePath -> FilePath)
setFrameName FilePath
n = (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath
" -F '(quote (name . \"" FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
n FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
"\"))' ") FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)

-- | Set the appropriate X class for a window.  This will more often
-- than not actually be the
-- <https://tronche.com/gui/x/icccm/sec-4.html#WM_CLASS instance name>.
setXClass :: String -> X Input
setXClass :: FilePath -> X (FilePath -> FilePath)
setXClass = (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath -> FilePath) -> X (FilePath -> FilePath))
-> (FilePath -> FilePath -> FilePath)
-> FilePath
-> X (FilePath -> FilePath)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> FilePath -> FilePath
mkDList (FilePath -> FilePath -> FilePath)
-> (FilePath -> FilePath) -> FilePath -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath
" --class " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)

-- | Spawn the 'XMonad.Core.XConfig.terminal' in some directory; it must
-- support the @--working-directory@ option.
termInDir :: X Input
termInDir :: X (FilePath -> FilePath)
termInDir = X (FilePath -> FilePath)
inTerm X (FilePath -> FilePath)
-> X (FilePath -> FilePath) -> X (FilePath -> FilePath)
>-> X (FilePath -> FilePath)
inWorkingDir

-- | Transform the given input into an elisp function; i.e., surround it
-- with parentheses.
--
-- >>> elispFun "arxiv-citation URL"
-- " '( arxiv-citation URL )' "
elispFun :: String -> String
elispFun :: FilePath -> FilePath
elispFun FilePath
f = FilePath
" '( " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
f FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
" )' "

-- | Treat an argument as a string; i.e., wrap it with quotes.
--
-- >>> asString "string"
-- " \"string\" "
asString :: String -> String
asString :: FilePath -> FilePath
asString FilePath
s = FilePath
" \"" FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
s FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
"\" "

-- | Wrap the given commands in a @progn@ and also escape it by wrapping
-- it inside single quotes.  The given commands need not be wrapped in
-- parentheses, this will be done by the function.  For example:
--
-- >>> progn [require "this-lib", "function-from-this-lib arg", "(other-function arg2)"]
-- " '( progn (require (quote this-lib)) (function-from-this-lib arg) (other-function arg2) )' "
progn :: [String] -> String
progn :: [FilePath] -> FilePath
progn [FilePath]
cmds = FilePath -> FilePath
elispFun (FilePath -> FilePath) -> FilePath -> FilePath
forall a b. (a -> b) -> a -> b
$ FilePath
"progn " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> [FilePath] -> FilePath
unwords ((FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map FilePath -> FilePath
inParens [FilePath]
cmds)

-- | Require a package.
--
-- >>> require "arxiv-citation"
-- "(require (quote arxiv-citation))"
require :: String -> String
require :: FilePath -> FilePath
require = FilePath -> FilePath
inParens (FilePath -> FilePath)
-> (FilePath -> FilePath) -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath
"require " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>) (FilePath -> FilePath)
-> (FilePath -> FilePath) -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> FilePath
quote

-- | Quote a symbol.
--
-- >>> quote "new-process"
-- "(quote new-process)"
quote :: String -> String
quote :: FilePath -> FilePath
quote = FilePath -> FilePath
inParens (FilePath -> FilePath)
-> (FilePath -> FilePath) -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath
"quote " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)

-----------------------------------------------------------------------
-- Batch mode

-- | Tell Emacs to enable batch-mode.
asBatch :: X Input
asBatch :: X (FilePath -> FilePath)
asBatch = (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FilePath
" --batch " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>)

-- | An Emacs library.
data EmacsLib
  = OwnFile !String
    -- ^ A /file/ from 'emacsLispDir'.
  | ElpaLib !String
    -- ^ A /directory/ in 'emacsElpaDir'.
  | Special !String
    -- ^ Special /files/; these will not be looked up somewhere, but
    -- forwarded verbatim (as a path).

-- | Load some Emacs libraries.  This is useful when executing scripts
-- in batch mode.
withEmacsLibs :: [EmacsLib] -> X Input
withEmacsLibs :: [EmacsLib] -> X (FilePath -> FilePath)
withEmacsLibs [EmacsLib]
libs = (ProcessConfig -> X (FilePath -> FilePath))
-> X (FilePath -> FilePath)
forall (m :: * -> *) a b.
(MonadReader XConf m, Typeable a, Default a) =>
(a -> m b) -> m b
XC.withDef ((ProcessConfig -> X (FilePath -> FilePath))
 -> X (FilePath -> FilePath))
-> (ProcessConfig -> X (FilePath -> FilePath))
-> X (FilePath -> FilePath)
forall a b. (a -> b) -> a -> b
$ \ProcessConfig{FilePath
emacsLispDir :: FilePath
emacsLispDir :: ProcessConfig -> FilePath
emacsLispDir, FilePath
emacsElpaDir :: FilePath
emacsElpaDir :: ProcessConfig -> FilePath
emacsElpaDir} -> do
  FilePath
lispDir <- FilePath -> X FilePath
forall (m :: * -> *). MonadIO m => FilePath -> m FilePath
mkAbsolutePath FilePath
emacsLispDir
  FilePath
elpaDir <- FilePath -> X FilePath
forall (m :: * -> *). MonadIO m => FilePath -> m FilePath
mkAbsolutePath FilePath
emacsElpaDir
  [FilePath]
lisp    <- IO [FilePath] -> X [FilePath]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO [FilePath] -> X [FilePath]) -> IO [FilePath] -> X [FilePath]
forall a b. (a -> b) -> a -> b
$ FilePath -> IO [FilePath]
getDirectoryContents FilePath
lispDir
  [FilePath]
elpa    <- IO [FilePath] -> X [FilePath]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO [FilePath] -> X [FilePath]) -> IO [FilePath] -> X [FilePath]
forall a b. (a -> b) -> a -> b
$ FilePath -> IO [FilePath]
getDirectoryContents FilePath
elpaDir

  let EmacsLib -> Maybe FilePath
getLib :: EmacsLib -> Maybe String = \case
        OwnFile FilePath
f -> ((FilePath
"-l " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
lispDir) FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>) (FilePath -> FilePath) -> Maybe FilePath -> Maybe FilePath
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (FilePath -> Bool) -> [FilePath] -> Maybe FilePath
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (FilePath
f          FilePath -> FilePath -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [FilePath]
lisp
        ElpaLib FilePath
d -> ((FilePath
"-L " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
elpaDir) FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<>) (FilePath -> FilePath) -> Maybe FilePath -> Maybe FilePath
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (FilePath -> Bool) -> [FilePath] -> Maybe FilePath
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((FilePath
d FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
"-") FilePath -> FilePath -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [FilePath]
elpa
        Special FilePath
f -> FilePath -> Maybe FilePath
forall a. a -> Maybe a
Just (FilePath -> Maybe FilePath) -> FilePath -> Maybe FilePath
forall a b. (a -> b) -> a -> b
$ FilePath
" -l " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
f
  (FilePath -> FilePath) -> X (FilePath -> FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((FilePath -> FilePath) -> X (FilePath -> FilePath))
-> ([EmacsLib] -> FilePath -> FilePath)
-> [EmacsLib]
-> X (FilePath -> FilePath)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> FilePath -> FilePath
mkDList (FilePath -> FilePath -> FilePath)
-> ([EmacsLib] -> FilePath) -> [EmacsLib] -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [FilePath] -> FilePath
unwords ([FilePath] -> FilePath)
-> ([EmacsLib] -> [FilePath]) -> [EmacsLib] -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (EmacsLib -> Maybe FilePath) -> [EmacsLib] -> [FilePath]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe EmacsLib -> Maybe FilePath
getLib ([EmacsLib] -> X (FilePath -> FilePath))
-> [EmacsLib] -> X (FilePath -> FilePath)
forall a b. (a -> b) -> a -> b
$ [EmacsLib]
libs

-----------------------------------------------------------------------
-- Util

mkDList :: String -> ShowS
mkDList :: FilePath -> FilePath -> FilePath
mkDList = FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
(<>) (FilePath -> FilePath -> FilePath)
-> (FilePath -> FilePath) -> FilePath -> FilePath -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
" ")

inParens :: String -> String
inParens :: FilePath -> FilePath
inParens FilePath
s = case FilePath
s of
  Char
'(' : FilePath
_ -> FilePath
s
  FilePath
_       -> FilePath
"(" FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
s FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
")"