Replace some [BR] in help texts with rst literals
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlinehelpmodule.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::CommandLineHelpModule.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_commandline
41  */
42 #include "gmxpre.h"
43
44 #include "cmdlinehelpmodule.h"
45
46 #include <string>
47 #include <vector>
48
49 #include <boost/scoped_ptr.hpp>
50
51 #include "gromacs/commandline/cmdlinehelpcontext.h"
52 #include "gromacs/commandline/cmdlinehelpwriter.h"
53 #include "gromacs/commandline/cmdlineparser.h"
54 #include "gromacs/onlinehelp/helpformat.h"
55 #include "gromacs/onlinehelp/helpmanager.h"
56 #include "gromacs/onlinehelp/helptopic.h"
57 #include "gromacs/onlinehelp/helpwritercontext.h"
58 #include "gromacs/options/basicoptions.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/utility/baseversion.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/file.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/programcontext.h"
65 #include "gromacs/utility/stringutil.h"
66
67 #include "shellcompletions.h"
68
69 namespace gmx
70 {
71
72 namespace
73 {
74 class HelpExportInterface;
75 class RootHelpTopic;
76 }   // namespace
77
78 /********************************************************************
79  * CommandLineHelpModuleImpl declaration
80  */
81
82 class CommandLineHelpModuleImpl
83 {
84     public:
85         CommandLineHelpModuleImpl(const ProgramContextInterface    &programContext,
86                                   const std::string                &binaryName,
87                                   const CommandLineModuleMap       &modules,
88                                   const CommandLineModuleGroupList &groups);
89
90         void exportHelp(HelpExportInterface *exporter) const;
91
92         boost::scoped_ptr<RootHelpTopic>  rootTopic_;
93         const ProgramContextInterface    &programContext_;
94         std::string                       binaryName_;
95         const CommandLineModuleMap       &modules_;
96         const CommandLineModuleGroupList &groups_;
97
98         CommandLineHelpContext           *context_;
99         const CommandLineModuleInterface *moduleOverride_;
100         bool                              bHidden_;
101
102         File                             *outputOverride_;
103
104         GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModuleImpl);
105 };
106
107 namespace
108 {
109
110 /********************************************************************
111  * RootHelpTopic
112  */
113
114 struct RootHelpText
115 {
116     static const char        name[];
117     static const char        title[];
118     static const char *const text[];
119 };
120
121 // The first two are not used.
122 const char        RootHelpText::name[]  = "";
123 const char        RootHelpText::title[] = "";
124 const char *const RootHelpText::text[]  = { "" };
125
126 /*! \brief
127  * Help topic that forms the root of the help tree for the help subcommand.
128  *
129  * \ingroup module_commandline
130  */
131 class RootHelpTopic : public CompositeHelpTopic<RootHelpText>
132 {
133     public:
134         /*! \brief
135          * Creates a root help topic.
136          *
137          * Does not throw.
138          */
139         explicit RootHelpTopic(const CommandLineHelpModuleImpl &helpModule)
140             : helpModule_(helpModule)
141         {
142         }
143
144         virtual void writeHelp(const HelpWriterContext &context) const;
145
146     private:
147         const CommandLineHelpModuleImpl  &helpModule_;
148
149         GMX_DISALLOW_COPY_AND_ASSIGN(RootHelpTopic);
150 };
151
152 void RootHelpTopic::writeHelp(const HelpWriterContext &context) const
153 {
154     if (context.outputFormat() != eHelpOutputFormat_Console)
155     {
156         // TODO: Implement once the situation with Redmine issue #969 is more
157         // clear.
158         GMX_THROW(NotImplementedError(
159                           "Root help is not implemented for this output format"));
160     }
161     {
162         CommandLineCommonOptionsHolder optionsHolder;
163         CommandLineHelpContext         cmdlineContext(*helpModule_.context_);
164         cmdlineContext.setModuleDisplayName(helpModule_.binaryName_);
165         optionsHolder.initOptions();
166         // TODO: Add <command> [<args>] into the synopsis.
167         CommandLineHelpWriter(*optionsHolder.options())
168             .writeHelp(cmdlineContext);
169     }
170     // TODO: Consider printing a list of "core" commands. Would require someone
171     // to determine such a set...
172     writeSubTopicList(context,
173                       "Additional help is available on the following topics:");
174     context.writeTextBlock("To access the help, use '[PROGRAM] help <topic>'.");
175     context.writeTextBlock("For help on a command, use '[PROGRAM] help <command>'.");
176 }
177
178 /********************************************************************
179  * CommandsHelpTopic
180  */
181
182 /*! \brief
183  * Help topic for listing the commands.
184  *
185  * \ingroup module_commandline
186  */
187 class CommandsHelpTopic : public HelpTopicInterface
188 {
189     public:
190         /*! \brief
191          * Creates a command list help topic.
192          *
193          * \param[in]     helpModule Help module to get module information from.
194          *
195          * Does not throw.
196          */
197         explicit CommandsHelpTopic(const CommandLineHelpModuleImpl &helpModule)
198             : helpModule_(helpModule)
199         {
200         }
201
202         virtual const char *name() const { return "commands"; }
203         virtual const char *title() const { return "List of available commands"; }
204         virtual bool hasSubTopics() const { return false; }
205         virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
206         {
207             return NULL;
208         }
209
210         virtual void writeHelp(const HelpWriterContext &context) const;
211
212     private:
213         const CommandLineHelpModuleImpl &helpModule_;
214
215         GMX_DISALLOW_COPY_AND_ASSIGN(CommandsHelpTopic);
216 };
217
218 void CommandsHelpTopic::writeHelp(const HelpWriterContext &context) const
219 {
220     if (context.outputFormat() != eHelpOutputFormat_Console)
221     {
222         GMX_THROW(NotImplementedError(
223                           "Module list is not implemented for this output format"));
224     }
225     int maxNameLength = 0;
226     const CommandLineModuleMap           &modules = helpModule_.modules_;
227     CommandLineModuleMap::const_iterator  module;
228     for (module = modules.begin(); module != modules.end(); ++module)
229     {
230         int nameLength = static_cast<int>(module->first.length());
231         if (module->second->shortDescription() != NULL
232             && nameLength > maxNameLength)
233         {
234             maxNameLength = nameLength;
235         }
236     }
237     context.writeTextBlock(
238             "Usage: [PROGRAM] [<options>] <command> [<args>][PAR]"
239             "Available commands:");
240     File              &file = context.outputFile();
241     TextTableFormatter formatter;
242     formatter.addColumn(NULL, maxNameLength + 1, false);
243     formatter.addColumn(NULL, 72 - maxNameLength, true);
244     formatter.setFirstColumnIndent(4);
245     for (module = modules.begin(); module != modules.end(); ++module)
246     {
247         const char *name        = module->first.c_str();
248         const char *description = module->second->shortDescription();
249         if (description != NULL)
250         {
251             formatter.clear();
252             formatter.addColumnLine(0, name);
253             formatter.addColumnLine(1, description);
254             file.writeString(formatter.formatRow());
255         }
256     }
257     context.writeTextBlock(
258             "For help on a command, use '[PROGRAM] help <command>'.");
259 }
260
261 /********************************************************************
262  * ModuleHelpTopic
263  */
264
265 /*! \brief
266  * Help topic wrapper for a command-line module.
267  *
268  * This class implements HelpTopicInterface such that it wraps a
269  * CommandLineModuleInterface, allowing subcommand "help <command>"
270  * to produce the help for "<command>".
271  *
272  * \ingroup module_commandline
273  */
274 class ModuleHelpTopic : public HelpTopicInterface
275 {
276     public:
277         //! Constructs a help topic for a specific module.
278         ModuleHelpTopic(const CommandLineModuleInterface &module,
279                         const CommandLineHelpModuleImpl  &helpModule)
280             : module_(module), helpModule_(helpModule)
281         {
282         }
283
284         virtual const char *name() const { return module_.name(); }
285         virtual const char *title() const { return NULL; }
286         virtual bool hasSubTopics() const { return false; }
287         virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
288         {
289             return NULL;
290         }
291         virtual void writeHelp(const HelpWriterContext &context) const;
292
293     private:
294         const CommandLineModuleInterface &module_;
295         const CommandLineHelpModuleImpl  &helpModule_;
296
297         GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
298 };
299
300 void ModuleHelpTopic::writeHelp(const HelpWriterContext & /*context*/) const
301 {
302     CommandLineHelpContext context(*helpModule_.context_);
303     const char *const      program = helpModule_.binaryName_.c_str();
304     context.setModuleDisplayName(formatString("%s %s", program, module_.name()));
305     module_.writeHelp(context);
306 }
307
308 /********************************************************************
309  * HelpExportInterface
310  */
311
312 /*! \brief
313  * Callbacks for exporting help information for command-line modules.
314  *
315  * \ingroup module_commandline
316  */
317 class HelpExportInterface
318 {
319     public:
320         //! Shorthand for a list of modules contained in a group.
321         typedef CommandLineModuleGroupData::ModuleList ModuleGroupContents;
322
323         virtual ~HelpExportInterface() {};
324
325         /*! \brief
326          * Called once before exporting individual modules.
327          *
328          * Can, e.g., open shared output files (e.g., if the output is written
329          * into a single file, or if a separate index is required) and write
330          * headers into them.
331          */
332         virtual void startModuleExport() = 0;
333         /*! \brief
334          * Called to export the help for each module.
335          *
336          * \param[in] module      Module for which the help should be exported.
337          * \param[in] tag         Unique tag for the module (gmx-something).
338          * \param[in] displayName Display name for the module (gmx something).
339          */
340         virtual void exportModuleHelp(
341             const CommandLineModuleInterface &module,
342             const std::string                &tag,
343             const std::string                &displayName) = 0;
344         /*! \brief
345          * Called after all modules have been exported.
346          *
347          * Can close files opened in startModuleExport(), write footers to them
348          * etc.
349          */
350         virtual void finishModuleExport() = 0;
351
352         /*! \brief
353          * Called once before exporting module groups.
354          *
355          * Can, e.g., open a single output file for listing all the groups.
356          */
357         virtual void startModuleGroupExport() = 0;
358         /*! \brief
359          * Called to export the help for each module group.
360          *
361          * \param[in] title    Title for the group.
362          * \param[in] modules  List of modules in the group.
363          */
364         virtual void exportModuleGroup(const char                *title,
365                                        const ModuleGroupContents &modules) = 0;
366         /*! \brief
367          * Called after all module groups have been exported.
368          *
369          * Can close files opened in startModuleGroupExport(), write footers to them
370          * etc.
371          */
372         virtual void finishModuleGroupExport() = 0;
373 };
374
375 /*! \internal \brief
376  * Adds hyperlinks to modules within this binary.
377  *
378  * \param[in,out] links      Links are added here.
379  * \param[in]     helpModule Help module to get module information from.
380  * \throws        std::bad_alloc if out of memory.
381  *
382  * Initializes a HelpLinks object with links to modules defined in
383  * \p helpModule.
384  *
385  * \ingroup module_commandline
386  */
387 void initProgramLinks(HelpLinks *links, const CommandLineHelpModuleImpl &helpModule)
388 {
389     const char *const                    program = helpModule.binaryName_.c_str();
390     CommandLineModuleMap::const_iterator module;
391     for (module = helpModule.modules_.begin();
392          module != helpModule.modules_.end();
393          ++module)
394     {
395         if (module->second->shortDescription() != NULL)
396         {
397             std::string linkName("[gmx-" + module->first + "]");
398             const char *name = module->first.c_str();
399             std::string reference(
400                     formatString(":doc:`%s %s <%s-%s>`", program, name, program, name));
401             std::string displayName(
402                     formatString("[TT]%s %s[tt]", program, name));
403             links->addLink(linkName, reference, displayName);
404         }
405     }
406 }
407
408 /********************************************************************
409  * HelpExportReStructuredText
410  */
411
412 /*! \internal \brief
413  * Implements export for web pages as reStructuredText.
414  *
415  * \ingroup module_commandline
416  */
417 class HelpExportReStructuredText : public HelpExportInterface
418 {
419     public:
420         //! Initializes reST exporter.
421         explicit HelpExportReStructuredText(
422             const CommandLineHelpModuleImpl &helpModule);
423
424         virtual void startModuleExport();
425         virtual void exportModuleHelp(
426             const CommandLineModuleInterface &module,
427             const std::string                &tag,
428             const std::string                &displayName);
429         virtual void finishModuleExport();
430
431         virtual void startModuleGroupExport();
432         virtual void exportModuleGroup(const char                *title,
433                                        const ModuleGroupContents &modules);
434         virtual void finishModuleGroupExport();
435
436     private:
437         HelpLinks                links_;
438         boost::scoped_ptr<File>  indexFile_;
439         boost::scoped_ptr<File>  manPagesFile_;
440 };
441
442 HelpExportReStructuredText::HelpExportReStructuredText(
443         const CommandLineHelpModuleImpl &helpModule)
444     : links_(eHelpOutputFormat_Rst)
445 {
446     File             linksFile("links.dat", "r");
447     std::string      line;
448     while (linksFile.readLine(&line))
449     {
450         links_.addLink("[REF]." + line + "[ref]",
451                        formatString(":ref:`.%s <%s>`", line.c_str(), line.c_str()),
452                        line);
453         links_.addLink("[REF]" + line + "[ref]", formatString(":ref:`%s`", line.c_str()), line);
454     }
455     linksFile.close();
456     initProgramLinks(&links_, helpModule);
457 }
458
459 void HelpExportReStructuredText::startModuleExport()
460 {
461     indexFile_.reset(new File("programs/byname.rst", "w"));
462     indexFile_->writeLine("Tools by Name");
463     indexFile_->writeLine("=============");
464     manPagesFile_.reset(new File("conf-man.py", "w"));
465     manPagesFile_->writeLine("man_pages = [");
466 }
467
468 void HelpExportReStructuredText::exportModuleHelp(
469         const CommandLineModuleInterface &module,
470         const std::string                &tag,
471         const std::string                &displayName)
472 {
473     // TODO: Ideally, the file would only be touched if it really changes.
474     // This would make Sphinx reruns much faster.
475     File file("programs/" + tag + ".rst", "w");
476     file.writeLine(formatString(".. _%s:", displayName.c_str()));
477     file.writeLine();
478     file.writeLine(displayName);
479     file.writeLine(std::string(displayName.length(), '='));
480     CommandLineHelpContext context(&file, eHelpOutputFormat_Rst, &links_);
481     context.setModuleDisplayName(displayName);
482     module.writeHelp(context);
483
484     file.writeLine();
485     file.writeLine(".. only:: man");
486     file.writeLine();
487     file.writeLine("   See also");
488     file.writeLine("   --------");
489     file.writeLine();
490     file.writeLine("   :manpage:`gromacs(7)`");
491     file.writeLine();
492     file.writeLine("   More information about |Gromacs| is available at <http://www.gromacs.org/>.");
493     file.close();
494
495     indexFile_->writeLine(formatString("* :doc:`%s <%s>` - %s",
496                                        displayName.c_str(), tag.c_str(),
497                                        module.shortDescription()));
498     manPagesFile_->writeLine(
499             formatString("    ('programs/%s', '%s', \"%s\", '', 1),",
500                          tag.c_str(), tag.c_str(), module.shortDescription()));
501 }
502
503 void HelpExportReStructuredText::finishModuleExport()
504 {
505     indexFile_->close();
506     indexFile_.reset();
507     manPagesFile_->writeLine("    ('man/gromacs.7', 'gromacs', 'molecular dynamics simulation suite', '', 7)");
508     manPagesFile_->writeLine("]");
509     manPagesFile_->close();
510     manPagesFile_.reset();
511 }
512
513 void HelpExportReStructuredText::startModuleGroupExport()
514 {
515     indexFile_.reset(new File("programs/bytopic.rst", "w"));
516     indexFile_->writeLine("Tools by Topic");
517     indexFile_->writeLine("==============");
518     manPagesFile_.reset(new File("man/bytopic.rst", "w"));
519 }
520
521 void HelpExportReStructuredText::exportModuleGroup(
522         const char                *title,
523         const ModuleGroupContents &modules)
524 {
525     indexFile_->writeLine(title);
526     indexFile_->writeLine(std::string(std::strlen(title), '-'));
527     manPagesFile_->writeLine(title);
528     manPagesFile_->writeLine(std::string(std::strlen(title), '+'));
529
530     ModuleGroupContents::const_iterator module;
531     for (module = modules.begin(); module != modules.end(); ++module)
532     {
533         const std::string     &tag(module->first);
534         std::string            displayName(tag);
535         // TODO: This does not work if the binary name would contain a dash,
536         // but that is not currently the case.
537         const size_t           dashPos = displayName.find('-');
538         GMX_RELEASE_ASSERT(dashPos != std::string::npos,
539                            "There should always be at least one dash in the tag");
540         displayName[dashPos] = ' ';
541         indexFile_->writeLine(formatString("| :doc:`%s <%s>` - %s",
542                                            displayName.c_str(), tag.c_str(),
543                                            module->second));
544         manPagesFile_->writeLine(formatString("| ``%s`` - %s",
545                                               displayName.c_str(),
546                                               module->second));
547     }
548     indexFile_->writeLine();
549     manPagesFile_->writeLine();
550 }
551
552 void HelpExportReStructuredText::finishModuleGroupExport()
553 {
554     indexFile_->close();
555     indexFile_.reset();
556     manPagesFile_->close();
557     manPagesFile_.reset();
558 }
559
560 /********************************************************************
561  * HelpExportCompletion
562  */
563
564 /*! \internal \brief
565  * Implements export for command-line completion.
566  *
567  * \ingroup module_commandline
568  */
569 class HelpExportCompletion : public HelpExportInterface
570 {
571     public:
572         //! Initializes completion exporter.
573         explicit HelpExportCompletion(const CommandLineHelpModuleImpl &helpModule);
574
575         virtual void startModuleExport();
576         virtual void exportModuleHelp(
577             const CommandLineModuleInterface &module,
578             const std::string                &tag,
579             const std::string                &displayName);
580         virtual void finishModuleExport();
581
582         virtual void startModuleGroupExport() {}
583         virtual void exportModuleGroup(const char                * /*title*/,
584                                        const ModuleGroupContents & /*modules*/) {}
585         virtual void finishModuleGroupExport() {}
586
587     private:
588         ShellCompletionWriter    bashWriter_;
589         std::vector<std::string> modules_;
590 };
591
592 HelpExportCompletion::HelpExportCompletion(
593         const CommandLineHelpModuleImpl &helpModule)
594     : bashWriter_(helpModule.binaryName_, eShellCompletionFormat_Bash)
595 {
596 }
597
598 void HelpExportCompletion::startModuleExport()
599 {
600     bashWriter_.startCompletions();
601 }
602
603 void HelpExportCompletion::exportModuleHelp(
604         const CommandLineModuleInterface &module,
605         const std::string                 & /*tag*/,
606         const std::string                 & /*displayName*/)
607 {
608     modules_.push_back(module.name());
609     {
610         CommandLineHelpContext context(&bashWriter_);
611         // We use the display name to pass the name of the module to the
612         // completion writer.
613         context.setModuleDisplayName(module.name());
614         module.writeHelp(context);
615     }
616 }
617
618 void HelpExportCompletion::finishModuleExport()
619 {
620     CommandLineCommonOptionsHolder optionsHolder;
621     optionsHolder.initOptions();
622     bashWriter_.writeWrapperCompletions(modules_, *optionsHolder.options());
623     bashWriter_.finishCompletions();
624 }
625
626 }   // namespace
627
628 /********************************************************************
629  * CommandLineHelpModuleImpl implementation
630  */
631 CommandLineHelpModuleImpl::CommandLineHelpModuleImpl(
632         const ProgramContextInterface    &programContext,
633         const std::string                &binaryName,
634         const CommandLineModuleMap       &modules,
635         const CommandLineModuleGroupList &groups)
636     : rootTopic_(new RootHelpTopic(*this)), programContext_(programContext),
637       binaryName_(binaryName), modules_(modules), groups_(groups),
638       context_(NULL), moduleOverride_(NULL), bHidden_(false),
639       outputOverride_(NULL)
640 {
641 }
642
643 void CommandLineHelpModuleImpl::exportHelp(HelpExportInterface *exporter) const
644 {
645     // TODO: Would be nicer to have the file names supplied by the build system
646     // and/or export a list of files from here.
647     const char *const program = binaryName_.c_str();
648
649     exporter->startModuleExport();
650     CommandLineModuleMap::const_iterator module;
651     for (module = modules_.begin(); module != modules_.end(); ++module)
652     {
653         if (module->second->shortDescription() != NULL)
654         {
655             const char *const moduleName = module->first.c_str();
656             std::string       tag(formatString("%s-%s", program, moduleName));
657             std::string       displayName(formatString("%s %s", program, moduleName));
658             exporter->exportModuleHelp(*module->second, tag, displayName);
659         }
660     }
661     exporter->finishModuleExport();
662
663     exporter->startModuleGroupExport();
664     CommandLineModuleGroupList::const_iterator group;
665     for (group = groups_.begin(); group != groups_.end(); ++group)
666     {
667         exporter->exportModuleGroup((*group)->title(), (*group)->modules());
668     }
669     exporter->finishModuleGroupExport();
670 }
671
672 /********************************************************************
673  * CommandLineHelpModule
674  */
675
676 CommandLineHelpModule::CommandLineHelpModule(
677         const ProgramContextInterface    &programContext,
678         const std::string                &binaryName,
679         const CommandLineModuleMap       &modules,
680         const CommandLineModuleGroupList &groups)
681     : impl_(new Impl(programContext, binaryName, modules, groups))
682 {
683 }
684
685 CommandLineHelpModule::~CommandLineHelpModule()
686 {
687 }
688
689 HelpTopicPointer CommandLineHelpModule::createModuleHelpTopic(
690         const CommandLineModuleInterface &module) const
691 {
692     return HelpTopicPointer(new ModuleHelpTopic(module, *impl_));
693 }
694
695 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
696 {
697     impl_->rootTopic_->addSubTopic(move(topic));
698 }
699
700 void CommandLineHelpModule::setShowHidden(bool bHidden)
701 {
702     impl_->bHidden_ = bHidden;
703 }
704
705 void CommandLineHelpModule::setModuleOverride(
706         const CommandLineModuleInterface &module)
707 {
708     impl_->moduleOverride_ = &module;
709 }
710
711 void CommandLineHelpModule::setOutputRedirect(File *output)
712 {
713     impl_->outputOverride_ = output;
714 }
715
716 int CommandLineHelpModule::run(int argc, char *argv[])
717 {
718     // Add internal topics lazily here.
719     addTopic(HelpTopicPointer(new CommandsHelpTopic(*impl_)));
720
721     const char *const exportFormats[] = { "rst", "completion" };
722     std::string       exportFormat;
723     Options           options(NULL, NULL);
724     options.addOption(StringOption("export").store(&exportFormat)
725                           .enumValue(exportFormats));
726     CommandLineParser(&options).parse(&argc, argv);
727     if (!exportFormat.empty())
728     {
729         boost::scoped_ptr<HelpExportInterface> exporter;
730         if (exportFormat == "rst")
731         {
732             exporter.reset(new HelpExportReStructuredText(*impl_));
733         }
734         else if (exportFormat == "completion")
735         {
736             exporter.reset(new HelpExportCompletion(*impl_));
737         }
738         else
739         {
740             GMX_THROW(NotImplementedError("This help format is not implemented"));
741         }
742         impl_->exportHelp(exporter.get());
743         return 0;
744     }
745
746     File *outputFile = &File::standardOutput();
747     if (impl_->outputOverride_ != NULL)
748     {
749         outputFile = impl_->outputOverride_;
750     }
751     HelpLinks                                 links(eHelpOutputFormat_Console);
752     initProgramLinks(&links, *impl_);
753     boost::scoped_ptr<CommandLineHelpContext> context(
754             new CommandLineHelpContext(outputFile,
755                                        eHelpOutputFormat_Console, &links));
756     context->setShowHidden(impl_->bHidden_);
757     if (impl_->moduleOverride_ != NULL)
758     {
759         context->setModuleDisplayName(impl_->programContext_.displayName());
760         impl_->moduleOverride_->writeHelp(*context);
761         return 0;
762     }
763     impl_->context_ = context.get();
764
765     HelpManager helpManager(*impl_->rootTopic_, context->writerContext());
766     try
767     {
768         for (int i = 1; i < argc; ++i)
769         {
770             helpManager.enterTopic(argv[i]);
771         }
772     }
773     catch (const InvalidInputError &ex)
774     {
775         fprintf(stderr, "%s\n", ex.what());
776         return 2;
777     }
778     helpManager.writeCurrentTopic();
779     return 0;
780 }
781
782 void CommandLineHelpModule::writeHelp(const CommandLineHelpContext &context) const
783 {
784     const HelpWriterContext &writerContext = context.writerContext();
785     // TODO: Implement.
786     if (writerContext.outputFormat() != eHelpOutputFormat_Console)
787     {
788         return;
789     }
790     writerContext.writeTextBlock(
791             "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
792     // TODO: More information.
793 }
794
795 } // namespace gmx