90f5ebab3b865aa0c054ba173bc7e57078c9aa82
[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(
175             "To access the help, use '[PROGRAM] help <topic>'.[BR]"
176             "For help on a command, use '[PROGRAM] help <command>'.");
177 }
178
179 /********************************************************************
180  * CommandsHelpTopic
181  */
182
183 /*! \brief
184  * Help topic for listing the commands.
185  *
186  * \ingroup module_commandline
187  */
188 class CommandsHelpTopic : public HelpTopicInterface
189 {
190     public:
191         /*! \brief
192          * Creates a command list help topic.
193          *
194          * \param[in]     helpModule Help module to get module information from.
195          *
196          * Does not throw.
197          */
198         explicit CommandsHelpTopic(const CommandLineHelpModuleImpl &helpModule)
199             : helpModule_(helpModule)
200         {
201         }
202
203         virtual const char *name() const { return "commands"; }
204         virtual const char *title() const { return "List of available commands"; }
205         virtual bool hasSubTopics() const { return false; }
206         virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
207         {
208             return NULL;
209         }
210
211         virtual void writeHelp(const HelpWriterContext &context) const;
212
213     private:
214         const CommandLineHelpModuleImpl &helpModule_;
215
216         GMX_DISALLOW_COPY_AND_ASSIGN(CommandsHelpTopic);
217 };
218
219 void CommandsHelpTopic::writeHelp(const HelpWriterContext &context) const
220 {
221     if (context.outputFormat() != eHelpOutputFormat_Console)
222     {
223         GMX_THROW(NotImplementedError(
224                           "Module list is not implemented for this output format"));
225     }
226     int maxNameLength = 0;
227     const CommandLineModuleMap           &modules = helpModule_.modules_;
228     CommandLineModuleMap::const_iterator  module;
229     for (module = modules.begin(); module != modules.end(); ++module)
230     {
231         int nameLength = static_cast<int>(module->first.length());
232         if (module->second->shortDescription() != NULL
233             && nameLength > maxNameLength)
234         {
235             maxNameLength = nameLength;
236         }
237     }
238     context.writeTextBlock(
239             "Usage: [PROGRAM] [<options>] <command> [<args>][PAR]"
240             "Available commands:");
241     File              &file = context.outputFile();
242     TextTableFormatter formatter;
243     formatter.addColumn(NULL, maxNameLength + 1, false);
244     formatter.addColumn(NULL, 72 - maxNameLength, true);
245     formatter.setFirstColumnIndent(4);
246     for (module = modules.begin(); module != modules.end(); ++module)
247     {
248         const char *name        = module->first.c_str();
249         const char *description = module->second->shortDescription();
250         if (description != NULL)
251         {
252             formatter.clear();
253             formatter.addColumnLine(0, name);
254             formatter.addColumnLine(1, description);
255             file.writeString(formatter.formatRow());
256         }
257     }
258     context.writeTextBlock(
259             "For help on a command, use '[PROGRAM] help <command>'.");
260 }
261
262 /********************************************************************
263  * ModuleHelpTopic
264  */
265
266 /*! \brief
267  * Help topic wrapper for a command-line module.
268  *
269  * This class implements HelpTopicInterface such that it wraps a
270  * CommandLineModuleInterface, allowing subcommand "help <command>"
271  * to produce the help for "<command>".
272  *
273  * \ingroup module_commandline
274  */
275 class ModuleHelpTopic : public HelpTopicInterface
276 {
277     public:
278         //! Constructs a help topic for a specific module.
279         ModuleHelpTopic(const CommandLineModuleInterface &module,
280                         const CommandLineHelpModuleImpl  &helpModule)
281             : module_(module), helpModule_(helpModule)
282         {
283         }
284
285         virtual const char *name() const { return module_.name(); }
286         virtual const char *title() const { return NULL; }
287         virtual bool hasSubTopics() const { return false; }
288         virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
289         {
290             return NULL;
291         }
292         virtual void writeHelp(const HelpWriterContext &context) const;
293
294     private:
295         const CommandLineModuleInterface &module_;
296         const CommandLineHelpModuleImpl  &helpModule_;
297
298         GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
299 };
300
301 void ModuleHelpTopic::writeHelp(const HelpWriterContext & /*context*/) const
302 {
303     CommandLineHelpContext context(*helpModule_.context_);
304     const char *const      program = helpModule_.binaryName_.c_str();
305     context.setModuleDisplayName(formatString("%s %s", program, module_.name()));
306     module_.writeHelp(context);
307 }
308
309 /********************************************************************
310  * HelpExportInterface
311  */
312
313 /*! \brief
314  * Callbacks for exporting help information for command-line modules.
315  *
316  * \ingroup module_commandline
317  */
318 class HelpExportInterface
319 {
320     public:
321         //! Shorthand for a list of modules contained in a group.
322         typedef CommandLineModuleGroupData::ModuleList ModuleGroupContents;
323
324         virtual ~HelpExportInterface() {};
325
326         /*! \brief
327          * Called once before exporting individual modules.
328          *
329          * Can, e.g., open shared output files (e.g., if the output is written
330          * into a single file, or if a separate index is required) and write
331          * headers into them.
332          */
333         virtual void startModuleExport() = 0;
334         /*! \brief
335          * Called to export the help for each module.
336          *
337          * \param[in] module      Module for which the help should be exported.
338          * \param[in] tag         Unique tag for the module (gmx-something).
339          * \param[in] displayName Display name for the module (gmx something).
340          */
341         virtual void exportModuleHelp(
342             const CommandLineModuleInterface &module,
343             const std::string                &tag,
344             const std::string                &displayName) = 0;
345         /*! \brief
346          * Called after all modules have been exported.
347          *
348          * Can close files opened in startModuleExport(), write footers to them
349          * etc.
350          */
351         virtual void finishModuleExport() = 0;
352
353         /*! \brief
354          * Called once before exporting module groups.
355          *
356          * Can, e.g., open a single output file for listing all the groups.
357          */
358         virtual void startModuleGroupExport() = 0;
359         /*! \brief
360          * Called to export the help for each module group.
361          *
362          * \param[in] title    Title for the group.
363          * \param[in] modules  List of modules in the group.
364          */
365         virtual void exportModuleGroup(const char                *title,
366                                        const ModuleGroupContents &modules) = 0;
367         /*! \brief
368          * Called after all module groups have been exported.
369          *
370          * Can close files opened in startModuleGroupExport(), write footers to them
371          * etc.
372          */
373         virtual void finishModuleGroupExport() = 0;
374 };
375
376 /*! \internal \brief
377  * Adds hyperlinks to modules within this binary.
378  *
379  * \param[in,out] links      Links are added here.
380  * \param[in]     helpModule Help module to get module information from.
381  * \throws        std::bad_alloc if out of memory.
382  *
383  * Initializes a HelpLinks object with links to modules defined in
384  * \p helpModule.
385  *
386  * \ingroup module_commandline
387  */
388 void initProgramLinks(HelpLinks *links, const CommandLineHelpModuleImpl &helpModule)
389 {
390     const char *const                    program = helpModule.binaryName_.c_str();
391     CommandLineModuleMap::const_iterator module;
392     for (module = helpModule.modules_.begin();
393          module != helpModule.modules_.end();
394          ++module)
395     {
396         if (module->second->shortDescription() != NULL)
397         {
398             std::string linkName("[gmx-" + module->first + "]");
399             std::string targetName(
400                     formatString("%s-%s", program, module->first.c_str()));
401             std::string displayName(
402                     formatString("[TT]%s %s[tt]", program, module->first.c_str()));
403             links->addLink(linkName, targetName, displayName);
404         }
405     }
406 }
407
408 /********************************************************************
409  * HelpExportHtml
410  */
411
412 /*! \internal
413  * \brief
414  * Implements export for HTML help.
415  *
416  * This whole class can go once docs/old-html/ no longer requires header.html
417  * that it generates.
418  *
419  * \ingroup module_commandline
420  */
421 class HelpExportHtml : public HelpExportInterface
422 {
423     public:
424         //! Initializes HTML exporter.
425         HelpExportHtml();
426
427         virtual void startModuleExport() {}
428         virtual void exportModuleHelp(
429             const CommandLineModuleInterface & /*module*/,
430             const std::string                & /*tag*/,
431             const std::string                & /*displayName*/) {}
432         virtual void finishModuleExport() {}
433
434         virtual void startModuleGroupExport() {}
435         virtual void exportModuleGroup(const char                * /*title*/,
436                                        const ModuleGroupContents & /*modules*/) {}
437         virtual void finishModuleGroupExport() {}
438 };
439
440 HelpExportHtml::HelpExportHtml()
441 {
442     std::string header = gmx::File::readToString("header.html.in");
443     header = replaceAll(header, "@VERSION@", gmx_version());
444     gmx::File::writeFileFromString("header.html", header);
445 }
446
447 /********************************************************************
448  * HelpExportReStructuredText
449  */
450
451 /*! \internal \brief
452  * Implements export for web pages as reStructuredText.
453  *
454  * \ingroup module_commandline
455  */
456 class HelpExportReStructuredText : public HelpExportInterface
457 {
458     public:
459         //! Initializes reST exporter.
460         explicit HelpExportReStructuredText(
461             const CommandLineHelpModuleImpl &helpModule);
462
463         virtual void startModuleExport();
464         virtual void exportModuleHelp(
465             const CommandLineModuleInterface &module,
466             const std::string                &tag,
467             const std::string                &displayName);
468         virtual void finishModuleExport();
469
470         virtual void startModuleGroupExport();
471         virtual void exportModuleGroup(const char                *title,
472                                        const ModuleGroupContents &modules);
473         virtual void finishModuleGroupExport();
474
475     private:
476         HelpLinks                links_;
477         boost::scoped_ptr<File>  indexFile_;
478         boost::scoped_ptr<File>  manPagesFile_;
479 };
480
481 HelpExportReStructuredText::HelpExportReStructuredText(
482         const CommandLineHelpModuleImpl &helpModule)
483     : links_(eHelpOutputFormat_Rst)
484 {
485 #if 0       // TODO: Investigate how these links can be made to work again.
486     File             linksFile("links.dat", "r");
487     std::string      line;
488     while (linksFile.readLine(&line))
489     {
490         links_.addLink(line, "../online/" + line, line);
491     }
492     linksFile.close();
493 #endif
494     initProgramLinks(&links_, helpModule);
495 }
496
497 void HelpExportReStructuredText::startModuleExport()
498 {
499     indexFile_.reset(new File("programs/byname.rst", "w"));
500     indexFile_->writeLine("Tools by Name");
501     indexFile_->writeLine("=============");
502     manPagesFile_.reset(new File("conf-man.py", "w"));
503     manPagesFile_->writeLine("man_pages = [");
504 }
505
506 void HelpExportReStructuredText::exportModuleHelp(
507         const CommandLineModuleInterface &module,
508         const std::string                &tag,
509         const std::string                &displayName)
510 {
511     // TODO: Ideally, the file would only be touched if it really changes.
512     // This would make Sphinx reruns much faster.
513     File file("programs/" + tag + ".rst", "w");
514     file.writeLine(formatString(".. _%s:", displayName.c_str()));
515     file.writeLine();
516     file.writeLine(displayName);
517     file.writeLine(std::string(displayName.length(), '='));
518     CommandLineHelpContext context(&file, eHelpOutputFormat_Rst, &links_);
519     context.setModuleDisplayName(displayName);
520     module.writeHelp(context);
521
522     file.writeLine();
523     file.writeLine(".. only:: man");
524     file.writeLine();
525     file.writeLine("   See also");
526     file.writeLine("   --------");
527     file.writeLine();
528     file.writeLine("   :manpage:`gromacs(7)`");
529     file.writeLine();
530     file.writeLine("   More information about |Gromacs| is available at <http://www.gromacs.org/>.");
531     file.close();
532
533     indexFile_->writeLine(formatString("* :doc:`%s <%s>` - %s",
534                                        displayName.c_str(), tag.c_str(),
535                                        module.shortDescription()));
536     manPagesFile_->writeLine(
537             formatString("    ('programs/%s', '%s', \"%s\", '', 1),",
538                          tag.c_str(), tag.c_str(), module.shortDescription()));
539 }
540
541 void HelpExportReStructuredText::finishModuleExport()
542 {
543     indexFile_->close();
544     indexFile_.reset();
545     manPagesFile_->writeLine("    ('man/gromacs.7', 'gromacs', 'molecular dynamics simulation suite', '', 7)");
546     manPagesFile_->writeLine("]");
547     manPagesFile_->close();
548     manPagesFile_.reset();
549 }
550
551 void HelpExportReStructuredText::startModuleGroupExport()
552 {
553     indexFile_.reset(new File("programs/bytopic.rst", "w"));
554     indexFile_->writeLine("Tools by Topic");
555     indexFile_->writeLine("==============");
556     manPagesFile_.reset(new File("man/bytopic.rst", "w"));
557 }
558
559 void HelpExportReStructuredText::exportModuleGroup(
560         const char                *title,
561         const ModuleGroupContents &modules)
562 {
563     indexFile_->writeLine(title);
564     indexFile_->writeLine(std::string(std::strlen(title), '-'));
565     manPagesFile_->writeLine(title);
566     manPagesFile_->writeLine(std::string(std::strlen(title), '+'));
567
568     ModuleGroupContents::const_iterator module;
569     for (module = modules.begin(); module != modules.end(); ++module)
570     {
571         const std::string     &tag(module->first);
572         std::string            displayName(tag);
573         // TODO: This does not work if the binary name would contain a dash,
574         // but that is not currently the case.
575         const size_t           dashPos = displayName.find('-');
576         GMX_RELEASE_ASSERT(dashPos != std::string::npos,
577                            "There should always be at least one dash in the tag");
578         displayName[dashPos] = ' ';
579         indexFile_->writeLine(formatString("| :doc:`%s <%s>` - %s",
580                                            displayName.c_str(), tag.c_str(),
581                                            module->second));
582         manPagesFile_->writeLine(formatString("| ``%s`` - %s",
583                                               displayName.c_str(),
584                                               module->second));
585     }
586     indexFile_->writeLine();
587     manPagesFile_->writeLine();
588 }
589
590 void HelpExportReStructuredText::finishModuleGroupExport()
591 {
592     indexFile_->close();
593     indexFile_.reset();
594     manPagesFile_->close();
595     manPagesFile_.reset();
596 }
597
598 /********************************************************************
599  * HelpExportCompletion
600  */
601
602 /*! \internal \brief
603  * Implements export for command-line completion.
604  *
605  * \ingroup module_commandline
606  */
607 class HelpExportCompletion : public HelpExportInterface
608 {
609     public:
610         //! Initializes completion exporter.
611         explicit HelpExportCompletion(const CommandLineHelpModuleImpl &helpModule);
612
613         virtual void startModuleExport();
614         virtual void exportModuleHelp(
615             const CommandLineModuleInterface &module,
616             const std::string                &tag,
617             const std::string                &displayName);
618         virtual void finishModuleExport();
619
620         virtual void startModuleGroupExport() {}
621         virtual void exportModuleGroup(const char                * /*title*/,
622                                        const ModuleGroupContents & /*modules*/) {}
623         virtual void finishModuleGroupExport() {}
624
625     private:
626         ShellCompletionWriter    bashWriter_;
627         std::vector<std::string> modules_;
628 };
629
630 HelpExportCompletion::HelpExportCompletion(
631         const CommandLineHelpModuleImpl &helpModule)
632     : bashWriter_(helpModule.binaryName_, eShellCompletionFormat_Bash)
633 {
634 }
635
636 void HelpExportCompletion::startModuleExport()
637 {
638     bashWriter_.startCompletions();
639 }
640
641 void HelpExportCompletion::exportModuleHelp(
642         const CommandLineModuleInterface &module,
643         const std::string                 & /*tag*/,
644         const std::string                 & /*displayName*/)
645 {
646     modules_.push_back(module.name());
647     {
648         CommandLineHelpContext context(&bashWriter_);
649         // We use the display name to pass the name of the module to the
650         // completion writer.
651         context.setModuleDisplayName(module.name());
652         module.writeHelp(context);
653     }
654 }
655
656 void HelpExportCompletion::finishModuleExport()
657 {
658     CommandLineCommonOptionsHolder optionsHolder;
659     optionsHolder.initOptions();
660     bashWriter_.writeWrapperCompletions(modules_, *optionsHolder.options());
661     bashWriter_.finishCompletions();
662 }
663
664 }   // namespace
665
666 /********************************************************************
667  * CommandLineHelpModuleImpl implementation
668  */
669 CommandLineHelpModuleImpl::CommandLineHelpModuleImpl(
670         const ProgramContextInterface    &programContext,
671         const std::string                &binaryName,
672         const CommandLineModuleMap       &modules,
673         const CommandLineModuleGroupList &groups)
674     : rootTopic_(new RootHelpTopic(*this)), programContext_(programContext),
675       binaryName_(binaryName), modules_(modules), groups_(groups),
676       context_(NULL), moduleOverride_(NULL), bHidden_(false),
677       outputOverride_(NULL)
678 {
679 }
680
681 void CommandLineHelpModuleImpl::exportHelp(HelpExportInterface *exporter) const
682 {
683     // TODO: Would be nicer to have the file names supplied by the build system
684     // and/or export a list of files from here.
685     const char *const program = binaryName_.c_str();
686
687     exporter->startModuleExport();
688     CommandLineModuleMap::const_iterator module;
689     for (module = modules_.begin(); module != modules_.end(); ++module)
690     {
691         if (module->second->shortDescription() != NULL)
692         {
693             const char *const moduleName = module->first.c_str();
694             std::string       tag(formatString("%s-%s", program, moduleName));
695             std::string       displayName(formatString("%s %s", program, moduleName));
696             exporter->exportModuleHelp(*module->second, tag, displayName);
697         }
698     }
699     exporter->finishModuleExport();
700
701     exporter->startModuleGroupExport();
702     CommandLineModuleGroupList::const_iterator group;
703     for (group = groups_.begin(); group != groups_.end(); ++group)
704     {
705         exporter->exportModuleGroup((*group)->title(), (*group)->modules());
706     }
707     exporter->finishModuleGroupExport();
708 }
709
710 /********************************************************************
711  * CommandLineHelpModule
712  */
713
714 CommandLineHelpModule::CommandLineHelpModule(
715         const ProgramContextInterface    &programContext,
716         const std::string                &binaryName,
717         const CommandLineModuleMap       &modules,
718         const CommandLineModuleGroupList &groups)
719     : impl_(new Impl(programContext, binaryName, modules, groups))
720 {
721 }
722
723 CommandLineHelpModule::~CommandLineHelpModule()
724 {
725 }
726
727 HelpTopicPointer CommandLineHelpModule::createModuleHelpTopic(
728         const CommandLineModuleInterface &module) const
729 {
730     return HelpTopicPointer(new ModuleHelpTopic(module, *impl_));
731 }
732
733 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
734 {
735     impl_->rootTopic_->addSubTopic(move(topic));
736 }
737
738 void CommandLineHelpModule::setShowHidden(bool bHidden)
739 {
740     impl_->bHidden_ = bHidden;
741 }
742
743 void CommandLineHelpModule::setModuleOverride(
744         const CommandLineModuleInterface &module)
745 {
746     impl_->moduleOverride_ = &module;
747 }
748
749 void CommandLineHelpModule::setOutputRedirect(File *output)
750 {
751     impl_->outputOverride_ = output;
752 }
753
754 int CommandLineHelpModule::run(int argc, char *argv[])
755 {
756     // Add internal topics lazily here.
757     addTopic(HelpTopicPointer(new CommandsHelpTopic(*impl_)));
758
759     const char *const exportFormats[] = { "html", "rst", "completion" };
760     std::string       exportFormat;
761     Options           options(NULL, NULL);
762     options.addOption(StringOption("export").store(&exportFormat)
763                           .enumValue(exportFormats));
764     CommandLineParser(&options).parse(&argc, argv);
765     if (!exportFormat.empty())
766     {
767         boost::scoped_ptr<HelpExportInterface> exporter;
768         if (exportFormat == "html")
769         {
770             exporter.reset(new HelpExportHtml());
771         }
772         else if (exportFormat == "rst")
773         {
774             exporter.reset(new HelpExportReStructuredText(*impl_));
775         }
776         else if (exportFormat == "completion")
777         {
778             exporter.reset(new HelpExportCompletion(*impl_));
779         }
780         else
781         {
782             GMX_THROW(NotImplementedError("This help format is not implemented"));
783         }
784         impl_->exportHelp(exporter.get());
785         return 0;
786     }
787
788     File *outputFile = &File::standardOutput();
789     if (impl_->outputOverride_ != NULL)
790     {
791         outputFile = impl_->outputOverride_;
792     }
793     HelpLinks                                 links(eHelpOutputFormat_Console);
794     initProgramLinks(&links, *impl_);
795     boost::scoped_ptr<CommandLineHelpContext> context(
796             new CommandLineHelpContext(outputFile,
797                                        eHelpOutputFormat_Console, &links));
798     context->setShowHidden(impl_->bHidden_);
799     if (impl_->moduleOverride_ != NULL)
800     {
801         context->setModuleDisplayName(impl_->programContext_.displayName());
802         impl_->moduleOverride_->writeHelp(*context);
803         return 0;
804     }
805     impl_->context_ = context.get();
806
807     HelpManager helpManager(*impl_->rootTopic_, context->writerContext());
808     try
809     {
810         for (int i = 1; i < argc; ++i)
811         {
812             helpManager.enterTopic(argv[i]);
813         }
814     }
815     catch (const InvalidInputError &ex)
816     {
817         fprintf(stderr, "%s\n", ex.what());
818         return 2;
819     }
820     helpManager.writeCurrentTopic();
821     return 0;
822 }
823
824 void CommandLineHelpModule::writeHelp(const CommandLineHelpContext &context) const
825 {
826     const HelpWriterContext &writerContext = context.writerContext();
827     // TODO: Implement.
828     if (writerContext.outputFormat() != eHelpOutputFormat_Console)
829     {
830         return;
831     }
832     writerContext.writeTextBlock(
833             "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
834     // TODO: More information.
835 }
836
837 } // namespace gmx