Include selection keyword details in user guide
[alexxy/gromacs.git] / src / gromacs / selection / selhelp.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009,2010,2011,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 functions in selhelp.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 #include "gmxpre.h"
43
44 #include "selhelp.h"
45
46 #include <set>
47 #include <string>
48 #include <utility>
49 #include <vector>
50
51 #include <boost/scoped_ptr.hpp>
52
53 #include "gromacs/onlinehelp/helptopic.h"
54 #include "gromacs/onlinehelp/helpwritercontext.h"
55 #include "gromacs/utility/exceptions.h"
56 #include "gromacs/utility/file.h"
57 #include "gromacs/utility/gmxassert.h"
58 #include "gromacs/utility/stringutil.h"
59
60 #include "selmethod.h"
61 #include "symrec.h"
62
63 namespace
64 {
65
66 struct CommonHelpText
67 {
68     static const char        name[];
69     static const char        title[];
70     static const char *const text[];
71 };
72
73 const char        CommonHelpText::name[]  = "selections";
74 const char        CommonHelpText::title[] =
75     "Selection syntax and usage";
76 const char *const CommonHelpText::text[] = {
77     "Selections are used to select atoms/molecules/residues for analysis.",
78     "In contrast to traditional index files, selections can be dynamic, i.e.,",
79     "select different atoms for different trajectory frames. The GROMACS",
80     "manual contains a short introductory section to selections in the",
81     "Analysis chapter, including suggestions on how to get familiar with",
82     "selections if you are new to the concept. The subtopics listed below",
83     "provide more details on the technical and syntactic aspects of",
84     "selections.[PAR]",
85
86     "Each analysis tool requires a different number of selections and the",
87     "selections are interpreted differently. The general idea is still the",
88     "same: each selection evaluates to a set of positions, where a position",
89     "can be an atom position or center-of-mass or center-of-geometry of",
90     "a set of atoms. The tool then uses these positions for its analysis to",
91     "allow very flexible processing. Some analysis tools may have limitations",
92     "on the types of selections allowed."
93 };
94
95 struct ArithmeticHelpText
96 {
97     static const char        name[];
98     static const char        title[];
99     static const char *const text[];
100 };
101
102 const char        ArithmeticHelpText::name[]  = "arithmetic";
103 const char        ArithmeticHelpText::title[] =
104     "Arithmetic expressions in selections";
105 const char *const ArithmeticHelpText::text[] = {
106     "Basic arithmetic evaluation is supported for numeric expressions.",
107     "Supported operations are addition, subtraction, negation, multiplication,",
108     "division, and exponentiation (using ^).",
109     "Result of a division by zero or other illegal operations is undefined.",
110 };
111
112 struct CmdLineHelpText
113 {
114     static const char        name[];
115     static const char        title[];
116     static const char *const text[];
117 };
118
119 const char        CmdLineHelpText::name[]  = "cmdline";
120 const char        CmdLineHelpText::title[] =
121     "Specifying selections from command line";
122 const char *const CmdLineHelpText::text[] = {
123     "If no selections are provided on the command line, you are prompted to",
124     "type the selections interactively (a pipe can also be used to provide",
125     "the selections in this case for most tools). While this works well for",
126     "testing, it is easier to provide the selections from the command line",
127     "if they are complex or for scripting.[PAR]",
128
129     "Each tool has different command-line arguments for specifying selections",
130     "(listed by [TT][PROGRAM] help <tool>[tt]).",
131     "You can either pass a single string containing all selections (separated",
132     "by semicolons), or multiple strings, each containing one selection.",
133     "Note that you need to quote the selections to protect them from the",
134     "shell.[PAR]",
135
136     "If you set a selection command-line argument, but do not provide any",
137     "selections, you are prompted to type the selections for that argument",
138     "interactively. This is useful if that selection argument is optional,",
139     "in which case it is not normally prompted for.[PAR]",
140
141     "To provide selections from a file, use [TT]-sf file.dat[tt] in the place",
142     "of the selection for a selection argument (e.g.,",
143     "[TT]-select -sf file.dat[tt]). In general, the [TT]-sf[tt] argument reads",
144     "selections from the provided file and assigns them to selection arguments",
145     "that have been specified up to that point, but for which no selections",
146     "have been provided.",
147     "As a special case, [TT]-sf[tt] provided on its own, without preceding",
148     "selection arguments, assigns the selections to all (yet unset) required",
149     "selections (i.e., those that would be promted interactively if no",
150     "selections are provided on the command line).[PAR]",
151
152     "To use groups from a traditional index file, use argument [TT]-n[tt]",
153     "to provide a file. See the \"syntax\" subtopic for how to use them.",
154     "If this option is not provided, default groups are generated.",
155     "The default groups are generated by reading selections from a file",
156     "[TT]defselection.dat[tt]. If such a file is found in the current",
157     "directory, it is used instead of the one provided by default.[PAR]",
158
159     "Depending on the tool, two additional command-line arguments may be",
160     "available to control the behavior:",
161     "",
162     "* [TT]-seltype[tt] can be used to specify the default type of",
163     "  positions to calculate for each selection.",
164     "* [TT]-selrpos[tt] can be used to specify the default type of",
165     "  positions used in selecting atoms by coordinates.",
166     "",
167     "See the \"positions\" subtopic for more information on these options.",
168 };
169
170 struct EvaluationHelpText
171 {
172     static const char        name[];
173     static const char        title[];
174     static const char *const text[];
175 };
176
177 const char        EvaluationHelpText::name[]  = "evaluation";
178 const char        EvaluationHelpText::title[] =
179     "Selection evaluation and optimization";
180 const char *const EvaluationHelpText::text[] = {
181     "Boolean evaluation proceeds from left to right and is short-circuiting",
182     "i.e., as soon as it is known whether an atom will be selected, the",
183     "remaining expressions are not evaluated at all.",
184     "This can be used to optimize the selections: you should write the",
185     "most restrictive and/or the most inexpensive expressions first in",
186     "boolean expressions.",
187     "The relative ordering between dynamic and static expressions does not",
188     "matter: all static expressions are evaluated only once, before the first",
189     "frame, and the result becomes the leftmost expression.[PAR]",
190
191     "Another point for optimization is in common subexpressions: they are not",
192     "automatically recognized, but can be manually optimized by the use of",
193     "variables. This can have a big impact on the performance of complex",
194     "selections, in particular if you define several index groups like this::",
195     "",
196     "  rdist = distance from com of resnr 1 to 5;",
197     "  resname RES and rdist < 2;",
198     "  resname RES and rdist < 4;",
199     "  resname RES and rdist < 6;",
200     "",
201     "Without the variable assignment, the distances would be evaluated three",
202     "times, although they are exactly the same within each selection.",
203     "Anything assigned into a variable becomes a common subexpression that",
204     "is evaluated only once during a frame.",
205     "Currently, in some cases the use of variables can actually lead to a small",
206     "performance loss because of the checks necessary to determine for which",
207     "atoms the expression has already been evaluated, but this should not be",
208     "a major problem.",
209 };
210
211 struct ExamplesHelpText
212 {
213     static const char        name[];
214     static const char        title[];
215     static const char *const text[];
216 };
217
218 const char        ExamplesHelpText::name[]  = "examples";
219 const char        ExamplesHelpText::title[] =
220     "Selection examples";
221 const char *const ExamplesHelpText::text[] = {
222     // TODO: Once there are more tools available, use examples that invoke
223     // tools and explain what the selections do in those tools.
224     "Below, examples of increasingly complex selections are given.[PAR]",
225
226     "Selection of all water oxygens::",
227     "",
228     "  resname SOL and name OW",
229     "",
230
231     "Centers of mass of residues 1 to 5 and 10::",
232     "",
233     "  res_com of resnr 1 to 5 10",
234     "",
235
236     "All atoms farther than 1 nm of a fixed position::",
237     "",
238     "  not within 1 of [1.2, 3.1, 2.4]",
239     "",
240
241     "All atoms of a residue LIG within 0.5 nm of a protein (with a custom name)::",
242     "",
243     "  \"Close to protein\" resname LIG and within 0.5 of group \"Protein\"",
244     "",
245
246     "All protein residues that have at least one atom within 0.5 nm of a residue LIG::",
247     "",
248     "  group \"Protein\" and same residue as within 0.5 of resname LIG",
249     "",
250
251     "All RES residues whose COM is between 2 and 4 nm from the COM of all of them::",
252     "",
253     "  rdist = res_com distance from com of resname RES",
254     "  resname RES and rdist >= 2 and rdist <= 4",
255     "",
256
257     "Selection like C1 C2 C2 C3 C3 C4 ... C8 C9 (e.g., for g_bond)::",
258     "",
259     "  name \"C[1-8]\" merge name \"C[2-9]\"",
260 };
261
262 struct KeywordsHelpText
263 {
264     static const char        name[];
265     static const char        title[];
266     static const char *const text[];
267 };
268
269 const char        KeywordsHelpText::name[]  = "keywords";
270 const char        KeywordsHelpText::title[] =
271     "Selection keywords";
272 const char *const KeywordsHelpText::text[] = {
273     "The following selection keywords are currently available.",
274     "For keywords marked with a star, additional help is available through",
275     "a subtopic KEYWORD, where KEYWORD is the name of the keyword.",
276 };
277
278 struct LimitationsHelpText
279 {
280     static const char        name[];
281     static const char        title[];
282     static const char *const text[];
283 };
284
285 const char        LimitationsHelpText::name[]  = "limitations";
286 const char        LimitationsHelpText::title[] =
287     "Selection limitations";
288 const char *const LimitationsHelpText::text[] = {
289     "* Some analysis programs may require a special structure for the input",
290     "  selections (e.g., some options of [TT]gmx gangle[tt] require the index",
291     "  group to be made of groups of three or four atoms).",
292     "  For such programs, it is up to the user to provide a proper selection",
293     "  expression that always returns such positions.",
294     "",
295     "* All selection keywords select atoms in increasing order, i.e., you can",
296     "  consider them as set operations that in the end return the atoms in",
297     "  sorted numerical order.  For example, the following selections select",
298     "  the same atoms in the same order::",
299     "",
300     "    resname RA RB RC",
301     "    resname RB RC RA",
302     "",
303     "  ::",
304     "",
305     "    atomnr 10 11 12 13",
306     "    atomnr 12 13 10 11",
307     "    atomnr 10 to 13",
308     "    atomnr 13 to 10",
309     "",
310     "  If you need atoms/positions in a different order, you can:",
311     "",
312     "  * use external index groups (for some static selections),",
313     "  * use the [TT]permute[tt] keyword to change the final order, or",
314     "  * use the [TT]merge[tt] or [TT]plus[tt] keywords to compose the",
315     "    final selection from multiple distinct selections.",
316     "",
317     "* Due to technical reasons, having a negative value as the first value in",
318     "  expressions like ::",
319     "",
320     "    charge -1 to -0.7",
321     "",
322     "  result in a syntax error. A workaround is to write ::",
323     "",
324     "    charge {-1 to -0.7}",
325     "",
326     "  instead.",
327     "",
328     "* When [TT]name[tt] selection keyword is used together with PDB input",
329     "  files, the behavior may be unintuitive. When GROMACS reads in a PDB",
330     "  file, 4 character atom names that start with a digit are transformed",
331     "  such that, e.g., 1HG2 becomes HG21, and the latter is what is matched",
332     "  by the [TT]name[tt] keyword. Use [TT]pdbname[tt] to match the atom name",
333     "  as it appears in the input PDB file.",
334 };
335
336 struct PositionsHelpText
337 {
338     static const char        name[];
339     static const char        title[];
340     static const char *const text[];
341 };
342
343 const char        PositionsHelpText::name[]  = "positions";
344 const char        PositionsHelpText::title[] =
345     "Specifying positions in selections";
346 const char *const PositionsHelpText::text[] = {
347     "Possible ways of specifying positions in selections are:[PAR]",
348
349     "1. A constant position can be defined as [TT][XX, YY, ZZ][tt], where",
350     "[TT]XX[tt], [TT]YY[tt] and [TT]ZZ[tt] are real numbers.[PAR]",
351
352     "2. [TT]com of ATOM_EXPR [pbc][tt] or [TT]cog of ATOM_EXPR [pbc][tt]",
353     "calculate the center of mass/geometry of [TT]ATOM_EXPR[tt]. If",
354     "[TT]pbc[tt] is specified, the center is calculated iteratively to try",
355     "to deal with cases where [TT]ATOM_EXPR[tt] wraps around periodic",
356     "boundary conditions.[PAR]",
357
358     "3. [TT]POSTYPE of ATOM_EXPR[tt] calculates the specified positions for",
359     "the atoms in [TT]ATOM_EXPR[tt].",
360     "[TT]POSTYPE[tt] can be [TT]atom[tt], [TT]res_com[tt], [TT]res_cog[tt],",
361     "[TT]mol_com[tt] or [TT]mol_cog[tt], with an optional prefix [TT]whole_[tt]",
362     "[TT]part_[tt] or [TT]dyn_[tt].",
363     "[TT]whole_[tt] calculates the centers for the whole residue/molecule,",
364     "even if only part of it is selected.",
365     "[TT]part_[tt] prefix calculates the centers for the selected atoms, but",
366     "uses always the same atoms for the same residue/molecule. The used atoms",
367     "are determined from the the largest group allowed by the selection.",
368     "[TT]dyn_[tt] calculates the centers strictly only for the selected atoms.",
369     "If no prefix is specified, whole selections default to [TT]part_[tt] and",
370     "other places default to [TT]whole_[tt].",
371     "The latter is often desirable to select the same molecules in different",
372     "tools, while the first is a compromise between speed ([TT]dyn_[tt]",
373     "positions can be slower to evaluate than [TT]part_[tt]) and intuitive",
374     "behavior.[PAR]",
375
376     "4. [TT]ATOM_EXPR[tt], when given for whole selections, is handled as 3.",
377     "above, using the position type from the command-line argument",
378     "[TT]-seltype[tt].[PAR]",
379
380     "Selection keywords that select atoms based on their positions, such as",
381     "[TT]dist from[tt], use by default the positions defined by the",
382     "[TT]-selrpos[tt] command-line option.",
383     "This can be overridden by prepending a [TT]POSTYPE[tt] specifier to the",
384     "keyword. For example, [TT]res_com dist from POS[tt] evaluates the",
385     "residue center of mass distances. In the example, all atoms of a residue",
386     "are either selected or not, based on the single distance calculated.",
387 };
388
389 struct SyntaxHelpText
390 {
391     static const char        name[];
392     static const char        title[];
393     static const char *const text[];
394 };
395
396 const char        SyntaxHelpText::name[]  = "syntax";
397 const char        SyntaxHelpText::title[] =
398     "Selection syntax";
399 const char *const SyntaxHelpText::text[] = {
400     "A set of selections consists of one or more selections, separated by",
401     "semicolons. Each selection defines a set of positions for the analysis.",
402     "Each selection can also be preceded by a string that gives a name for",
403     "the selection for use in, e.g., graph legends.",
404     "If no name is provided, the string used for the selection is used",
405     "automatically as the name.[PAR]",
406
407     "For interactive input, the syntax is slightly altered: line breaks can",
408     "also be used to separate selections. \\ followed by a line break can",
409     "be used to continue a line if necessary.",
410     "Notice that the above only applies to real interactive input,",
411     "not if you provide the selections, e.g., from a pipe.[PAR]",
412
413     "It is possible to use variables to store selection expressions.",
414     "A variable is defined with the following syntax::",
415     "",
416     "  VARNAME = EXPR ;",
417     "",
418     "where [TT]EXPR[tt] is any valid selection expression.",
419     "After this, [TT]VARNAME[tt] can be used anywhere where [TT]EXPR[tt]",
420     "would be valid.[PAR]",
421
422     "Selections are composed of three main types of expressions, those that",
423     "define atoms ([TT]ATOM_EXPR[tt]), those that define positions",
424     "([TT]POS_EXPR[tt]), and those that evaluate to numeric values",
425     "([TT]NUM_EXPR[tt]). Each selection should be a [TT]POS_EXPR[tt]",
426     "or a [TT]ATOM_EXPR[tt] (the latter is automatically converted to",
427     "positions). The basic rules are as follows:",
428     "",
429     "* An expression like [TT]NUM_EXPR1 < NUM_EXPR2[tt] evaluates to an",
430     "  [TT]ATOM_EXPR[tt] that selects all the atoms for which the comparison",
431     "  is true.",
432     "* Atom expressions can be combined with boolean operations such as",
433     "  [TT]not ATOM_EXPR[tt], [TT]ATOM_EXPR and ATOM_EXPR[tt], or",
434     "  [TT]ATOM_EXPR or ATOM_EXPR[tt]. Parentheses can be used to alter the",
435     "  evaluation order.",
436     "* [TT]ATOM_EXPR[tt] expressions can be converted into [TT]POS_EXPR[tt]",
437     "  expressions in various ways, see the \"positions\" subtopic for more",
438     "  details.",
439     "* [TT]POS_EXPR[tt] can be converted into [TT]NUM_EXPR[tt] using syntax",
440     "  like \"[TT]x of POS_EXPR[tt]\". Currently, this is only supported for single",
441     "  positions like in expression \"[TT]x of cog of ATOM_EXPR[tt]\".",
442     "",
443
444     "Some keywords select atoms based on string values such as the atom name.",
445     "For these keywords, it is possible to use wildcards ([TT]name \"C*\"[tt])",
446     "or regular expressions (e.g., [TT]resname \"R[AB]\"[tt]).",
447     "The match type is automatically guessed from the string: if it contains",
448     "other characters than letters, numbers, '*', or '?', it is interpreted",
449     "as a regular expression.",
450     "To force the matching to use literal string matching, use",
451     "[TT]name = \"C*\"[tt] to match a literal C*.",
452     "To force other type of matching, use '?' or '~' in place of '=' to force",
453     "wildcard or regular expression matching, respectively.[PAR]",
454
455     "Strings that contain non-alphanumeric characters should be enclosed in",
456     "double quotes as in the examples. For other strings, the quotes are",
457     "optional, but if the value conflicts with a reserved keyword, a syntax",
458     "error will occur. If your strings contain uppercase letters, this should",
459     "not happen.[PAR]",
460
461     "Index groups provided with the [TT]-n[tt] command-line option or",
462     "generated by default can be accessed with [TT]group NR[tt] or",
463     "[TT]group NAME[tt], where [TT]NR[tt] is a zero-based index of the group",
464     "and [TT]NAME[tt] is part of the name of the desired group.",
465     "The keyword [TT]group[tt] is optional if the whole selection is",
466     "provided from an index group.",
467     "To see a list of available groups in the interactive mode, press enter",
468     "in the beginning of a line.",
469 };
470
471 } // namespace
472
473 namespace gmx
474 {
475
476 namespace
477 {
478
479 /*! \internal \brief
480  * Help topic implementation for an individual selection method.
481  *
482  * \ingroup module_selection
483  */
484 class KeywordDetailsHelpTopic : public AbstractSimpleHelpTopic
485 {
486     public:
487         //! Initialize help topic for the given selection method.
488         KeywordDetailsHelpTopic(const std::string         &name,
489                                 const gmx_ana_selmethod_t &method)
490             : name_(name), method_(method)
491         {
492         }
493
494         virtual const char *name() const
495         {
496             return name_.c_str();
497         }
498         virtual const char *title() const
499         {
500             return method_.help.helpTitle;
501         }
502
503     protected:
504         virtual std::string helpText() const
505         {
506             return joinStrings(method_.help.help,
507                                method_.help.help + method_.help.nlhelp, "\n");
508         }
509
510     private:
511         std::string                name_;
512         const gmx_ana_selmethod_t &method_;
513
514         GMX_DISALLOW_COPY_AND_ASSIGN(KeywordDetailsHelpTopic);
515 };
516
517 /*! \internal \brief
518  * Custom help topic for printing a list of selection keywords.
519  *
520  * \ingroup module_selection
521  */
522 class KeywordsHelpTopic : public CompositeHelpTopic<KeywordsHelpText>
523 {
524     public:
525         KeywordsHelpTopic();
526
527         virtual void writeHelp(const HelpWriterContext &context) const;
528
529     private:
530         /*! \brief
531          * Container for known selection methods.
532          *
533          * The first item in the pair is the name of the selection method, and
534          * the second points to the static data structure that describes the
535          * method.
536          * The name in the first item may differ from the name of the static
537          * data structure if an alias is defined for that method.
538          */
539         typedef std::vector<std::pair<std::string,
540                                       const gmx_ana_selmethod_t *> >
541             MethodList;
542
543         /*! \brief
544          * Prints markup for starting a list of keywords.
545          */
546         void writeKeywordListStart(const HelpWriterContext &context,
547                                    const char              *heading) const;
548         /*! \brief
549          * Prints markup for ending a list of keywords.
550          */
551         void writeKeywordListEnd(const HelpWriterContext &context,
552                                  const char              *extraInfo) const;
553
554         /*! \brief
555          * Prints a brief list of keywords (selection methods) available.
556          *
557          * \param[in] context  Context for printing the help.
558          * \param[in] type     Only methods that return this type are printed.
559          * \param[in] bModifiers  If false, \ref SMETH_MODIFIER methods are
560          *      excluded, otherwise only them are printed.
561          */
562         void printKeywordList(const HelpWriterContext &context,
563                               e_selvalue_t type, bool bModifiers) const;
564
565         /*! \brief
566          * Prints the detailed help for keywords for rst export.
567          */
568         void writeKeywordSubTopics(const HelpWriterContext &context) const;
569
570         MethodList              methods_;
571 };
572
573 KeywordsHelpTopic::KeywordsHelpTopic()
574 {
575     // TODO: This is not a very elegant way of getting the list of selection
576     // methods, but this needs to be rewritten in any case if/when #652 is
577     // implemented.
578     boost::scoped_ptr<SelectionParserSymbolTable> symtab(
579             new SelectionParserSymbolTable);
580     gmx_ana_selmethod_register_defaults(symtab.get());
581
582     SelectionParserSymbolIterator symbol
583         = symtab->beginIterator(SelectionParserSymbol::MethodSymbol);
584     while (symbol != symtab->endIterator())
585     {
586         const std::string         &symname = symbol->name();
587         const gmx_ana_selmethod_t *method  = symbol->methodValue();
588         methods_.push_back(std::make_pair(std::string(symname), method));
589         if (method->help.nlhelp > 0 && method->help.help != NULL)
590         {
591             addSubTopic(HelpTopicPointer(
592                                 new KeywordDetailsHelpTopic(symname, *method)));
593         }
594         ++symbol;
595     }
596 }
597
598 void KeywordsHelpTopic::writeHelp(const HelpWriterContext &context) const
599 {
600     context.writeTextBlock(helpText());
601     context.writeTextBlock("");
602
603     // Print the list of keywords
604     writeKeywordListStart(context, "Keywords that select atoms by an integer property:");
605     printKeywordList(context, INT_VALUE, false);
606     writeKeywordListEnd(context, "(use in expressions or like \"atomnr 1 to 5 7 9\")");
607
608     writeKeywordListStart(context, "Keywords that select atoms by a numeric property:");
609     printKeywordList(context, REAL_VALUE, false);
610     writeKeywordListEnd(context, "(use in expressions or like \"occupancy 0.5 to 1\")");
611
612     writeKeywordListStart(context, "Keywords that select atoms by a string property:");
613     printKeywordList(context, STR_VALUE, false);
614     writeKeywordListEnd(context, "(use like \"name PATTERN [PATTERN] ...\")");
615
616     writeKeywordListStart(context, "Additional keywords that directly select atoms:");
617     printKeywordList(context, GROUP_VALUE, false);
618     writeKeywordListEnd(context, NULL);
619
620     writeKeywordListStart(context, "Keywords that directly evaluate to positions:");
621     printKeywordList(context, POS_VALUE, false);
622     writeKeywordListEnd(context, "(see also \"positions\" subtopic)");
623
624     writeKeywordListStart(context, "Additional keywords:");
625     printKeywordList(context, POS_VALUE, true);
626     printKeywordList(context, NO_VALUE, true);
627     writeKeywordListEnd(context, NULL);
628
629     writeKeywordSubTopics(context);
630 }
631
632 void KeywordsHelpTopic::writeKeywordListStart(const HelpWriterContext &context,
633                                               const char              *heading) const
634 {
635     context.writeTextBlock(heading);
636     if (context.outputFormat() == eHelpOutputFormat_Rst)
637     {
638         context.writeTextBlock("");
639         context.writeTextBlock("::");
640         context.writeTextBlock("");
641     }
642 }
643
644 void KeywordsHelpTopic::writeKeywordListEnd(const HelpWriterContext &context,
645                                             const char              *extraInfo) const
646 {
647     if (context.outputFormat() == eHelpOutputFormat_Rst)
648     {
649         context.writeTextBlock("");
650     }
651     if (!isNullOrEmpty(extraInfo))
652     {
653         context.writeTextBlock(extraInfo);
654     }
655     context.writeTextBlock("");
656 }
657
658 void KeywordsHelpTopic::printKeywordList(const HelpWriterContext &context,
659                                          e_selvalue_t             type,
660                                          bool                     bModifiers) const
661 {
662     File &file = context.outputFile();
663     MethodList::const_iterator iter;
664     for (iter = methods_.begin(); iter != methods_.end(); ++iter)
665     {
666         const gmx_ana_selmethod_t &method = *iter->second;
667         const bool                 bIsModifier
668             = (method.flags & SMETH_MODIFIER) != 0;
669         if (method.type == type && bModifiers == bIsModifier)
670         {
671             const bool bHasHelp = (method.help.nlhelp > 0 && method.help.help != NULL);
672             const bool bPrintStar
673                 = bHasHelp && context.outputFormat() == eHelpOutputFormat_Console;
674             file.writeString(formatString(" %c ", bPrintStar ? '*' : ' '));
675             if (method.help.syntax != NULL)
676             {
677                 file.writeLine(method.help.syntax);
678             }
679             else
680             {
681                 std::string symname = iter->first;
682                 if (symname != method.name)
683                 {
684                     symname.append(formatString(" (synonym for %s)", method.name));
685                 }
686                 file.writeLine(symname);
687             }
688         }
689     }
690 }
691
692 void KeywordsHelpTopic::writeKeywordSubTopics(const HelpWriterContext &context) const
693 {
694     if (context.outputFormat() != eHelpOutputFormat_Rst)
695     {
696         return;
697     }
698     std::set<std::string>      usedSymbols;
699     MethodList::const_iterator iter;
700     for (iter = methods_.begin(); iter != methods_.end(); ++iter)
701     {
702         const gmx_ana_selmethod_t &method = *iter->second;
703         const bool                 bHasHelp
704             = (method.help.nlhelp > 0 && method.help.help != NULL);
705         if (!bHasHelp || usedSymbols.count(iter->first) > 0)
706         {
707             continue;
708         }
709
710         std::string                title;
711         if (method.help.helpTitle != NULL)
712         {
713             title = method.help.helpTitle;
714             title.append(" - ");
715         }
716         title.append(iter->first);
717         MethodList::const_iterator mergeIter = iter;
718         for (++mergeIter; mergeIter != methods_.end(); ++mergeIter)
719         {
720             if (mergeIter->second->help.help == method.help.help)
721             {
722                 title.append(", ");
723                 title.append(mergeIter->first);
724                 usedSymbols.insert(mergeIter->first);
725             }
726         }
727
728         const HelpTopicInterface *subTopic = findSubTopic(iter->first.c_str());
729         GMX_RELEASE_ASSERT(subTopic != NULL, "Keyword subtopic no longer exists");
730         HelpWriterContext         subContext(context);
731         subContext.enterSubSection(title);
732         subTopic->writeHelp(subContext);
733         context.writeTextBlock("");
734     }
735 }
736
737 }   // namespace
738
739 //! \cond libapi */
740 HelpTopicPointer createSelectionHelpTopic()
741 {
742     CompositeHelpTopicPointer root(new CompositeHelpTopic<CommonHelpText>);
743     root->registerSubTopic<SimpleHelpTopic<CmdLineHelpText> >();
744     root->registerSubTopic<SimpleHelpTopic<SyntaxHelpText> >();
745     root->registerSubTopic<SimpleHelpTopic<PositionsHelpText> >();
746     root->registerSubTopic<SimpleHelpTopic<ArithmeticHelpText> >();
747     root->registerSubTopic<KeywordsHelpTopic>();
748     root->registerSubTopic<SimpleHelpTopic<EvaluationHelpText> >();
749     root->registerSubTopic<SimpleHelpTopic<LimitationsHelpText> >();
750     root->registerSubTopic<SimpleHelpTopic<ExamplesHelpText> >();
751     return move(root);
752 }
753 //! \endcond
754
755 } // namespace gmx