{-# OPTIONS_HADDOCK hide #-}
module Language.Hanspell.Glob (matchGlob, matchGlobs) where
import Text.Regex
import Data.Maybe
matchGlob :: String -> String -> Bool
matchGlob glob string = isJust (matchRegex (mkRegex (globToRegex glob)) string)
matchGlobs :: [String] -> String -> Bool
matchGlobs globs string = any (`matchGlob` string) globs
globToRegex :: String -> String
globToRegex globex = '^' : globToRegex' globex ++ "$"
globToRegex' :: String -> String
globToRegex' "" = ""
globToRegex' ('*':cs) = ".*" ++ globToRegex' cs
globToRegex' ('?':cs) = '.' : globToRegex' cs
globToRegex' ('[':'!':c:cs) = "[^" ++ c : charClass cs
globToRegex' ('[':c:cs) = '[' : c : charClass cs
globToRegex' ('[':_) = error "unterminated character class"
globToRegex' (c:cs) = escape c ++ globToRegex' cs
escape :: Char -> String
escape c | c `elem` regexChars = '\\' : [c]
| otherwise = [c]
where regexChars = "\\+()^$.{}]"
charClass :: String -> String
charClass (']':cs) = ']' : globToRegex' cs
charClass (c:cs) = c : charClass cs
charClass [] = error "unterminated character class"