Merge release-4-6 into release-5-0
[alexxy/gromacs.git] / src / gromacs / commandline / shellcompletions.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 /*! \internal \file
38  * \brief
39  * Implements gmx::ShellCompletionWriter.
40  *
41  * \author Teemu Murtola <teemu.murtola@gmail.com>
42  * \ingroup module_commandline
43  */
44 #include "gromacs/commandline/shellcompletions.h"
45
46 #include <cstdio>
47
48 #include <string>
49
50 #include <boost/scoped_ptr.hpp>
51
52 #include "gromacs/commandline/cmdlinehelpcontext.h"
53 #include "gromacs/commandline/pargs.h"
54 #include "gromacs/options/basicoptions.h"
55 #include "gromacs/options/filenameoption.h"
56 #include "gromacs/options/optionsvisitor.h"
57 #include "gromacs/fileio/filenm.h"
58 #include "gromacs/utility/arrayref.h"
59 #include "gromacs/utility/exceptions.h"
60 #include "gromacs/utility/file.h"
61 #include "gromacs/utility/gmxassert.h"
62 #include "gromacs/utility/stringutil.h"
63
64 namespace gmx
65 {
66
67 namespace
68 {
69
70 class OptionsListWriter : public OptionsVisitor
71 {
72     public:
73         const std::string &optionList() const { return optionList_; }
74
75         virtual void visitSubSection(const Options &section)
76         {
77             OptionsIterator iterator(section);
78             iterator.acceptSubSections(this);
79             iterator.acceptOptions(this);
80         }
81         virtual void visitOption(const OptionInfo &option)
82         {
83             if (option.isHidden())
84             {
85                 return;
86             }
87             if (!optionList_.empty())
88             {
89                 optionList_.append("\\n");
90             }
91             optionList_.append("-");
92             const BooleanOptionInfo *booleanOption
93                 = option.toType<BooleanOptionInfo>();
94             if (booleanOption != NULL && booleanOption->defaultValue())
95             {
96                 optionList_.append("no");
97             }
98             optionList_.append(option.name());
99         }
100
101     private:
102         std::string optionList_;
103 };
104
105 class OptionCompletionWriter : public OptionsVisitor
106 {
107     public:
108         explicit OptionCompletionWriter(File *out) : out_(*out) {}
109
110         virtual void visitSubSection(const Options &section)
111         {
112             OptionsIterator iterator(section);
113             iterator.acceptSubSections(this);
114             iterator.acceptOptions(this);
115         }
116         virtual void visitOption(const OptionInfo &option);
117
118     private:
119         void writeOptionCompletion(const OptionInfo  &option,
120                                    const std::string &completion);
121
122         File &out_;
123 };
124
125 void OptionCompletionWriter::visitOption(const OptionInfo &option)
126 {
127     if (option.isHidden())
128     {
129         return;
130     }
131     const FileNameOptionInfo *fileOption = option.toType<FileNameOptionInfo>();
132     if (fileOption != NULL)
133     {
134         if (fileOption->isDirectoryOption())
135         {
136             writeOptionCompletion(option, "compgen -S ' ' -d $c");
137             return;
138         }
139         const FileNameOptionInfo::ExtensionList &extensionList = fileOption->extensions();
140         if (extensionList.empty())
141         {
142             return;
143         }
144         std::string completion("compgen -S ' ' -X '!*");
145         std::string extensions(joinStrings(extensionList, "|"));
146         if (extensionList.size() > 1)
147         {
148             extensions = "@(" + extensions + ")";
149         }
150         completion.append(extensions);
151         // TODO: Don't duplicate this from filenm.c/futil.c.
152         completion.append("?(.gz|.Z)' -f -- $c ; compgen -S '/' -d $c");
153         writeOptionCompletion(option, completion);
154         return;
155     }
156     const StringOptionInfo *stringOption = option.toType<StringOptionInfo>();
157     if (stringOption != NULL && stringOption->isEnumerated())
158     {
159         std::string completion("compgen -S ' ' -W $'");
160         completion.append(joinStrings(stringOption->allowedValues(), "\\n"));
161         completion.append("' -- $c");
162         writeOptionCompletion(option, completion);
163         return;
164     }
165 }
166
167 void OptionCompletionWriter::writeOptionCompletion(
168         const OptionInfo &option, const std::string &completion)
169 {
170     std::string result(formatString("-%s) ", option.name().c_str()));
171     if (option.maxValueCount() >= 0)
172     {
173         result.append(formatString("(( $n <= %d )) && ", option.maxValueCount()));
174     }
175     result.append("COMPREPLY=( $(");
176     result.append(completion);
177     result.append("));;");
178     out_.writeLine(result);
179 }
180
181 }   // namespace
182
183 class ShellCompletionWriter::Impl
184 {
185     public:
186         Impl(const std::string &binaryName, ShellCompletionFormat /*format*/)
187             : binaryName_(binaryName)
188         {
189         }
190
191         std::string completionFunctionName(const char *moduleName) const
192         {
193             // TODO: Consider if some characters need to be escaped.
194             return formatString("_%s_%s_compl", binaryName_.c_str(), moduleName);
195         }
196
197         std::string             binaryName_;
198         boost::scoped_ptr<File> file_;
199 };
200
201 ShellCompletionWriter::ShellCompletionWriter(const std::string     &binaryName,
202                                              ShellCompletionFormat  format)
203     : impl_(new Impl(binaryName, format))
204 {
205 }
206
207 ShellCompletionWriter::~ShellCompletionWriter()
208 {
209 }
210
211 File *ShellCompletionWriter::outputFile()
212 {
213     return impl_->file_.get();
214 }
215
216 void ShellCompletionWriter::startCompletions()
217 {
218     impl_->file_.reset(new File(impl_->binaryName_ + "-completion.bash", "w"));
219     impl_->file_->writeLine("shopt -s extglob");
220 }
221
222 void ShellCompletionWriter::writeModuleCompletions(
223         const char    *moduleName,
224         const Options &options)
225 {
226     File &out = *impl_->file_;
227     out.writeLine(formatString("%s() {", impl_->completionFunctionName(moduleName).c_str()));
228     out.writeLine("local IFS=$'\\n'");
229     out.writeLine("local c=${COMP_WORDS[COMP_CWORD]}");
230     out.writeLine("local n");
231     out.writeLine("for ((n=1;n<COMP_CWORD;++n)) ; do [[ \"${COMP_WORDS[COMP_CWORD-n]}\" == -* ]] && break ; done");
232     out.writeLine("local p=${COMP_WORDS[COMP_CWORD-n]}");
233     out.writeLine("COMPREPLY=()");
234
235     OptionsListWriter listWriter;
236     listWriter.visitSubSection(options);
237     out.writeLine(formatString("if (( $COMP_CWORD <= 1 )) || [[ $c == -* ]]; then COMPREPLY=( $(compgen -S ' '  -W $'%s' -- $c)); return 0; fi", listWriter.optionList().c_str()));
238
239     out.writeLine("case \"$p\" in");
240     OptionCompletionWriter optionWriter(&out);
241     optionWriter.visitSubSection(options);
242     out.writeLine("esac }");
243 }
244
245 void ShellCompletionWriter::writeWrapperCompletions(
246         const ModuleNameList &modules, const Options &options)
247 {
248     impl_->file_->writeLine("_" + impl_->binaryName_ + "_compl() {");
249     impl_->file_->writeLine("local i c m");
250     impl_->file_->writeLine("local IFS=$'\\n'\n");
251     impl_->file_->writeLine("COMPREPLY=()");
252     impl_->file_->writeLine("unset COMP_WORDS[0]");
253     impl_->file_->writeLine("for ((i=1;i<COMP_CWORD;++i)) ; do");
254     impl_->file_->writeLine("[[ \"${COMP_WORDS[i]}\" != -* ]] && break");
255     impl_->file_->writeLine("unset COMP_WORDS[i]");
256     impl_->file_->writeLine("done");
257     impl_->file_->writeLine("if (( i == COMP_CWORD )); then");
258     impl_->file_->writeLine("c=${COMP_WORDS[COMP_CWORD]}");
259     OptionsListWriter lister;
260     lister.visitSubSection(options);
261     std::string       completions(lister.optionList());
262     for (ModuleNameList::const_iterator i = modules.begin();
263          i != modules.end(); ++i)
264     {
265         completions.append("\\n");
266         completions.append(*i);
267     }
268     impl_->file_->writeLine("COMPREPLY=( $(compgen -S ' ' -W $'" + completions + "' -- $c) )");
269     impl_->file_->writeLine("return 0");
270     impl_->file_->writeLine("fi");
271     impl_->file_->writeLine("m=${COMP_WORDS[i]}");
272     impl_->file_->writeLine("COMP_WORDS=( \"${COMP_WORDS[@]}\" )");
273     impl_->file_->writeLine("COMP_CWORD=$((COMP_CWORD-i))");
274     impl_->file_->writeLine("case \"$m\" in");
275     for (ModuleNameList::const_iterator i = modules.begin();
276          i != modules.end(); ++i)
277     {
278         const char *const name = i->c_str();
279         impl_->file_->writeLine(formatString("%s) %s ;;", name,
280                                              impl_->completionFunctionName(name).c_str()));
281     }
282     impl_->file_->writeLine("esac }");
283 }
284
285 void ShellCompletionWriter::finishCompletions()
286 {
287     impl_->file_->close();
288     impl_->file_.reset();
289 }
290
291 } // namespace gmx