@@ -17,8 +17,11 @@ import Prelude
1717#if !defined(__MHS__)
1818import Data.Foldable ( asum )
1919#endif
20+
21+ import qualified Data.Foldable as Foldable
2022import Data.List ( isPrefixOf )
21- import Data.Maybe ( fromMaybe , listToMaybe )
23+ import Data.List.NonEmpty (NonEmpty )
24+ import Data.Maybe ( fromMaybe , listToMaybe , mapMaybe )
2225
2326import Options.Applicative.Builder
2427import Options.Applicative.Common
@@ -120,7 +123,7 @@ bashCompletionQuery pinfo pprefs richness ws i _ = case runCompletion compl ppre
120123 | argumentIsUnreachable reachability
121124 -> return []
122125 | otherwise
123- -> return . with_cmd_help $ filter (is_completion . fst ) ns
126+ -> return . with_cmd_help $ filter_completions ns
124127
125128 -- When doing enriched completions, add any help specified
126129 -- to the completion variables (tab separated).
@@ -148,6 +151,30 @@ bashCompletionQuery pinfo pprefs richness ws i _ = case runCompletion compl ppre
148151 show_names :: [OptName ] -> [String ]
149152 show_names = filter is_completion . map showOption
150153
154+ -- Filter commands and aliases matching the completion e.g. if we have
155+ -- commands:
156+ --
157+ -- - ([retry], p1)
158+ -- - ([run, r, go], p2)
159+ -- - ([search], p3)
160+ --
161+ -- and the user types 'r', we should return
162+ --
163+ -- [(retry, p1), (run, p2)]
164+ --
165+ -- If the first entry (command name) is the canonical one, we should
166+ -- favour it in completions, as if we were to provide all options there
167+ -- would be a good chance we'd be forcing the user to tab through and
168+ -- disambiguate between functionally identical options.
169+ --
170+ -- In zsh and fish we also provide the help doc in the completions, which
171+ -- we don't want to repeat a whole bunch of times.
172+ filter_completions :: [(NonEmpty String , ParserInfo a )] -> [(String , ParserInfo a )]
173+ filter_completions =
174+ let findAlias :: (NonEmpty String , b ) -> Maybe (String , b )
175+ findAlias (aliases, painfo) = (\ x -> (x, painfo)) <$> Foldable. find is_completion aliases
176+ in mapMaybe findAlias
177+
151178 -- We only want to show a single line in the completion results description.
152179 -- If there was a line break, it would come across as a different completion
153180 -- possibility.
0 commit comments