{-# LANGUAGE DerivingVia #-}{-# LANGUAGE OverloadedLabels #-}{-# LANGUAGE OverloadedStrings #-}{-# OPTIONS_GHC -Wno-orphans #-}module Cornelis.Utils whereimport Control.Concurrent.Asyncimport Control.Exception (throwIO)import Control.Lens ((%~))import Control.Monad.IO.Unlift (MonadUnliftIO(withRunInIO))import Control.Monad.Reader (withReaderT)import Control.Monad.State.Classimport Cornelis.Typesimport qualified Data.Map as Mimport Data.Maybeimport Data.Text.Encoding (decodeUtf8)import Data.Traversableimport qualified Data.Vector as Vimport Neovim hiding (err)import Neovim.API.Textimport Neovim.Context.Internal (Neovim(..), retypeConfig)objectToInt :: Num a => Object -> Maybe aobjectToInt (ObjectUInt w) = Just $ fromIntegral wobjectToInt (ObjectInt w) = Just $ fromIntegral wobjectToInt _ = NothingobjectToText :: Object -> Maybe TextobjectToText (ObjectString w) = Just $ decodeUtf8 wobjectToText _ = NothingneovimAsync :: (MonadUnliftIO m) => m a -> m (Async a)neovimAsync m = withRunInIO $ \lower -> liftIO $ async $ lower msavingCurrentPosition :: Window -> Neovim env a -> Neovim env asavingCurrentPosition w m = do c <- window_get_cursor w m <* window_set_cursor w csavingCurrentWindow :: Neovim env a -> Neovim env asavingCurrentWindow m = do w <- nvim_get_current_win m <* nvim_set_current_win wwindowsForBuffer :: Buffer -> Neovim env [Window]windowsForBuffer b = do wins <- fmap V.toList vim_get_windows fmap catMaybes $ for wins $ \w -> do wb <- window_get_buffer w pure $ case wb == b of False -> Nothing True -> Just wvisibleBuffers :: Neovim env [(Window, Buffer)]visibleBuffers = do wins <- fmap V.toList vim_get_windows for wins $ \w -> fmap (w, ) $ window_get_buffer wcriticalFailure :: Text -> Neovim env acriticalFailure err = do vim_report_error err liftIO $ throwIO $ ErrorResult "critical error" ObjectNilmodifyBufferStuff :: Buffer -> (BufferStuff -> BufferStuff) -> Neovim CornelisEnv ()modifyBufferStuff b f = modify' $! #cs_buffers %~ M.update (Just . f) bwithBufferStuff :: Monoid a => Buffer -> (BufferStuff -> Neovim CornelisEnv a) -> Neovim CornelisEnv awithBufferStuff b f = gets (M.lookup b . cs_buffers) >>= \case Nothing -> vim_report_error "no buffer stuff!" >> pure mempty Just bs -> f bswithLocalEnv :: env -> Neovim env a -> Neovim env' awithLocalEnv env (Neovim t) = Neovim $ flip withReaderT t $ retypeConfig env