Merge release-4-6 into master
[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 #include "gromacs/commandline/shellcompletions.h"
38
39 #include <cstdio>
40
41 #include <string>
42
43 #include <boost/scoped_ptr.hpp>
44
45 #include "gromacs/commandline/cmdlinehelpcontext.h"
46 #include "gromacs/commandline/pargs.h"
47 #include "gromacs/options/basicoptions.h"
48 #include "gromacs/options/filenameoption.h"
49 #include "gromacs/options/optionsvisitor.h"
50 #include "gromacs/fileio/filenm.h"
51 #include "gromacs/utility/arrayref.h"
52 #include "gromacs/utility/exceptions.h"
53 #include "gromacs/utility/file.h"
54 #include "gromacs/utility/gmxassert.h"
55 #include "gromacs/utility/stringutil.h"
56
57 namespace gmx
58 {
59
60 namespace
61 {
62
63 class OptionsListWriter : public OptionsVisitor
64 {
65     public:
66         const std::string &optionList() const { return optionList_; }
67
68         virtual void visitSubSection(const Options &section)
69         {
70             OptionsIterator iterator(section);
71             iterator.acceptSubSections(this);
72             iterator.acceptOptions(this);
73         }
74         virtual void visitOption(const OptionInfo &option)
75         {
76             if (option.isHidden())
77             {
78                 return;
79             }
80             if (!optionList_.empty())
81             {
82                 optionList_.append("\\n");
83             }
84             optionList_.append("-");
85             const BooleanOptionInfo *booleanOption
86                 = option.toType<BooleanOptionInfo>();
87             if (booleanOption != NULL && booleanOption->defaultValue())
88             {
89                 optionList_.append("no");
90             }
91             optionList_.append(option.name());
92         }
93
94     private:
95         std::string optionList_;
96 };
97
98 class OptionCompletionWriter : public OptionsVisitor
99 {
100     public:
101         explicit OptionCompletionWriter(File *out) : out_(*out) {}
102
103         virtual void visitSubSection(const Options &section)
104         {
105             OptionsIterator iterator(section);
106             iterator.acceptSubSections(this);
107             iterator.acceptOptions(this);
108         }
109         virtual void visitOption(const OptionInfo &option);
110
111     private:
112         void writeOptionCompletion(const OptionInfo  &option,
113                                    const std::string &completion);
114
115         File &out_;
116 };
117
118 void OptionCompletionWriter::visitOption(const OptionInfo &option)
119 {
120     if (option.isHidden())
121     {
122         return;
123     }
124     const FileNameOptionInfo *fileOption = option.toType<FileNameOptionInfo>();
125     if (fileOption != NULL)
126     {
127         if (fileOption->isDirectoryOption())
128         {
129             writeOptionCompletion(option, "compgen -S ' ' -d $c");
130             return;
131         }
132         const FileNameOptionInfo::ExtensionList &extensionList = fileOption->extensions();
133         if (extensionList.empty())
134         {
135             return;
136         }
137         std::string completion("compgen -S ' ' -X '!*");
138         std::string extensions(joinStrings(extensionList, "|"));
139         if (extensionList.size() > 1)
140         {
141             extensions = "@(" + extensions + ")";
142         }
143         completion.append(extensions);
144         // TODO: Don't duplicate this from filenm.c/futil.c.
145         completion.append("?(.gz|.Z)' -f -- $c ; compgen -S '/' -d $c");
146         writeOptionCompletion(option, completion);
147         return;
148     }
149     const StringOptionInfo *stringOption = option.toType<StringOptionInfo>();
150     if (stringOption != NULL && stringOption->isEnumerated())
151     {
152         std::string completion("compgen -S ' ' -W $'");
153         completion.append(joinStrings(stringOption->allowedValues(), "\\n"));
154         completion.append("' -- $c");
155         writeOptionCompletion(option, completion);
156         return;
157     }
158 }
159
160 void OptionCompletionWriter::writeOptionCompletion(
161         const OptionInfo &option, const std::string &completion)
162 {
163     std::string result(formatString("-%s) ", option.name().c_str()));
164     if (option.maxValueCount() >= 0)
165     {
166         result.append(formatString("(( $n <= %d )) && ", option.maxValueCount()));
167     }
168     result.append("COMPREPLY=( $(");
169     result.append(completion);
170     result.append("));;");
171     out_.writeLine(result);
172 }
173
174 }   // namespace
175
176 class ShellCompletionWriter::Impl
177 {
178     public:
179         Impl(const std::string &binaryName, ShellCompletionFormat /*format*/)
180             : binaryName_(binaryName)
181         {
182         }
183
184         std::string completionFunctionName(const char *moduleName) const
185         {
186             // TODO: Consider if some characters need to be escaped.
187             return formatString("_%s_%s_compl", binaryName_.c_str(), moduleName);
188         }
189
190         std::string             binaryName_;
191         boost::scoped_ptr<File> file_;
192 };
193
194 ShellCompletionWriter::ShellCompletionWriter(const std::string     &binaryName,
195                                              ShellCompletionFormat  format)
196     : impl_(new Impl(binaryName, format))
197 {
198 }
199
200 ShellCompletionWriter::~ShellCompletionWriter()
201 {
202 }
203
204 File *ShellCompletionWriter::outputFile()
205 {
206     return impl_->file_.get();
207 }
208
209 void ShellCompletionWriter::startCompletions()
210 {
211     impl_->file_.reset(new File(impl_->binaryName_ + "-completion.bash", "w"));
212     impl_->file_->writeLine("shopt -s extglob");
213 }
214
215 void ShellCompletionWriter::writeModuleCompletions(
216         const char    *moduleName,
217         const Options &options)
218 {
219     File &out = *impl_->file_;
220     out.writeLine(formatString("%s() {", impl_->completionFunctionName(moduleName).c_str()));
221     out.writeLine("local IFS=$'\\n'");
222     out.writeLine("local c=${COMP_WORDS[COMP_CWORD]}");
223     out.writeLine("local n");
224     out.writeLine("for ((n=1;n<COMP_CWORD;++n)) ; do [[ \"${COMP_WORDS[COMP_CWORD-n]}\" == -* ]] && break ; done");
225     out.writeLine("local p=${COMP_WORDS[COMP_CWORD-n]}");
226     out.writeLine("COMPREPLY=()");
227
228     OptionsListWriter listWriter;
229     listWriter.visitSubSection(options);
230     out.writeLine(formatString("if (( $COMP_CWORD <= 1 )) || [[ $c == -* ]]; then COMPREPLY=( $(compgen -S ' '  -W $'%s' -- $c)); return 0; fi", listWriter.optionList().c_str()));
231
232     out.writeLine("case \"$p\" in");
233     OptionCompletionWriter optionWriter(&out);
234     optionWriter.visitSubSection(options);
235     out.writeLine("esac }");
236 }
237
238 void ShellCompletionWriter::writeWrapperCompletions(
239         const ModuleNameList &modules, const Options &options)
240 {
241     impl_->file_->writeLine("_" + impl_->binaryName_ + "_compl() {");
242     impl_->file_->writeLine("local i c m");
243     impl_->file_->writeLine("local IFS=$'\\n'\n");
244     impl_->file_->writeLine("COMPREPLY=()");
245     impl_->file_->writeLine("unset COMP_WORDS[0]");
246     impl_->file_->writeLine("for ((i=1;i<COMP_CWORD;++i)) ; do");
247     impl_->file_->writeLine("[[ \"${COMP_WORDS[i]}\" != -* ]] && break");
248     impl_->file_->writeLine("unset COMP_WORDS[i]");
249     impl_->file_->writeLine("done");
250     impl_->file_->writeLine("if (( i == COMP_CWORD )); then");
251     impl_->file_->writeLine("c=${COMP_WORDS[COMP_CWORD]}");
252     OptionsListWriter lister;
253     lister.visitSubSection(options);
254     std::string       completions(lister.optionList());
255     for (ModuleNameList::const_iterator i = modules.begin();
256          i != modules.end(); ++i)
257     {
258         completions.append("\\n");
259         completions.append(*i);
260     }
261     impl_->file_->writeLine("COMPREPLY=( $(compgen -S ' ' -W $'" + completions + "' -- $c) )");
262     impl_->file_->writeLine("return 0");
263     impl_->file_->writeLine("fi");
264     impl_->file_->writeLine("m=${COMP_WORDS[i]}");
265     impl_->file_->writeLine("COMP_WORDS=( \"${COMP_WORDS[@]}\" )");
266     impl_->file_->writeLine("COMP_CWORD=$((COMP_CWORD-i))");
267     impl_->file_->writeLine("case \"$m\" in");
268     for (ModuleNameList::const_iterator i = modules.begin();
269          i != modules.end(); ++i)
270     {
271         const char *const name = i->c_str();
272         impl_->file_->writeLine(formatString("%s) %s ;;", name,
273                                              impl_->completionFunctionName(name).c_str()));
274     }
275     impl_->file_->writeLine("esac }");
276 }
277
278 void ShellCompletionWriter::finishCompletions()
279 {
280     impl_->file_->close();
281     impl_->file_.reset();
282 }
283
284 } // namespace gmx