|
| 1 | +module Ide.Plugin.StylishHaskell |
| 2 | + ( |
| 3 | + descriptor |
| 4 | + , provider |
| 5 | + ) |
| 6 | +where |
| 7 | + |
| 8 | +import Control.Monad.IO.Class |
| 9 | +import Data.Text (Text) |
| 10 | +import qualified Data.Text as T |
| 11 | +import Ide.Plugin.Formatter |
| 12 | +import Ide.PluginUtils |
| 13 | +import Ide.Types |
| 14 | +import Language.Haskell.Stylish |
| 15 | +import Language.Haskell.LSP.Types as J |
| 16 | + |
| 17 | +import System.Directory |
| 18 | +import System.FilePath |
| 19 | + |
| 20 | +descriptor :: PluginId -> PluginDescriptor |
| 21 | +descriptor plId = (defaultPluginDescriptor plId) |
| 22 | + { pluginFormattingProvider = Just provider |
| 23 | + } |
| 24 | + |
| 25 | +-- | Formatter provider of stylish-haskell. |
| 26 | +-- Formats the given source in either a given Range or the whole Document. |
| 27 | +-- If the provider fails an error is returned that can be displayed to the user. |
| 28 | +provider :: FormattingProvider IO |
| 29 | +provider _lf _ideState typ contents fp _opts = do |
| 30 | + let file = fromNormalizedFilePath fp |
| 31 | + config <- liftIO $ loadConfigFrom file |
| 32 | + let (range, selectedContents) = case typ of |
| 33 | + FormatText -> (fullRange contents, contents) |
| 34 | + FormatRange r -> (normalize r, extractRange r contents) |
| 35 | + result = runStylishHaskell file config selectedContents |
| 36 | + case result of |
| 37 | + Left err -> return $ Left $ responseError $ T.pack $ "stylishHaskellCmd: " ++ err |
| 38 | + Right new -> return $ Right $ J.List [TextEdit range new] |
| 39 | + |
| 40 | +-- | Recursively search in every directory of the given filepath for .stylish-haskell.yaml. |
| 41 | +-- If no such file has been found, return default config. |
| 42 | +loadConfigFrom :: FilePath -> IO Config |
| 43 | +loadConfigFrom file = do |
| 44 | + currDir <- getCurrentDirectory |
| 45 | + setCurrentDirectory (takeDirectory file) |
| 46 | + config <- loadConfig (makeVerbose False) Nothing |
| 47 | + setCurrentDirectory currDir |
| 48 | + return config |
| 49 | + |
| 50 | +-- | Run stylish-haskell on the given text with the given configuration. |
| 51 | +runStylishHaskell :: FilePath -- ^ Location of the file being formatted. Used for error message |
| 52 | + -> Config -- ^ Configuration for stylish-haskell |
| 53 | + -> Text -- ^ Text to format |
| 54 | + -> Either String Text -- ^ Either formatted Text or an error message |
| 55 | +runStylishHaskell file config = fmap fromLines . fmt . toLines |
| 56 | + where |
| 57 | + fromLines = T.pack . unlines |
| 58 | + fmt = runSteps (configLanguageExtensions config) (Just file) (configSteps config) |
| 59 | + toLines = lines . T.unpack |
0 commit comments