module Jikka.Common.Format.AutoIndent where

import Data.List (isPrefixOf, isSuffixOf)

indent :: String
indent :: String
indent = String
"<INDENT>"

dedent :: String
dedent :: String
dedent = String
"<DEDENT>"

makeIndentFromMarkers :: Int -> [String] -> [String]
makeIndentFromMarkers :: Int -> [String] -> [String]
makeIndentFromMarkers Int
size = Int -> [String] -> [String]
go Int
0
  where
    go :: Int -> [String] -> [String]
    go :: Int -> [String] -> [String]
go Int
_ [] = []
    go Int
n (String
line : [String]
lines)
      | String
line String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
indent = Int -> [String] -> [String]
go (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
size) [String]
lines
      | String
line String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
dedent = Int -> [String] -> [String]
go (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
size) [String]
lines
      | Bool
otherwise = (Int -> Char -> String
forall a. Int -> a -> [a]
replicate Int
n Char
' ' String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
line) String -> [String] -> [String]
forall a. a -> [a] -> [a]
: Int -> [String] -> [String]
go Int
n [String]
lines

makeIndentFromBraces :: Int -> [String] -> [String]
makeIndentFromBraces :: Int -> [String] -> [String]
makeIndentFromBraces Int
size = Int -> [String] -> [String]
makeIndentFromMarkers Int
size ([String] -> [String])
-> ([String] -> [String]) -> [String] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> [String]
insertIndentDedentFromBraces

insertIndentDedentFromBraces :: [String] -> [String]
insertIndentDedentFromBraces :: [String] -> [String]
insertIndentDedentFromBraces = (String -> [String]) -> [String] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap String -> [String]
go
  where
    go :: String -> [String]
    go :: String -> [String]
go String
line =
      let close :: [String]
close = if String
"}" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` String
line then [String
dedent] else []
          open :: [String]
open = if String
"{" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` String
line then [String
indent] else []
       in [String]
close [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String
line] [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
open