]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListingsParams.cpp
prepare Qt 5.6 builds
[lyx.git] / src / insets / InsetListingsParams.cpp
1 /**
2  * \file InsetListingsParams.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Bo Peng
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12 #include <algorithm>
13
14 #include "InsetListingsParams.h"
15
16 #include "Length.h"
17 #include "Lexer.h"
18
19 #include "support/convert.h"
20 #include "support/gettext.h"
21 #include "support/lstrings.h"
22 #include "support/textutils.h"
23
24 #include <sstream>
25
26 using namespace std;
27 using namespace lyx::support;
28
29 namespace lyx {
30
31 namespace {
32
33 enum param_type {
34         ALL,  // accept all
35         TRUEFALSE, // accept 'true' or 'false'
36         INTEGER, // accept an integer
37         LENGTH,  // accept a latex length
38         SKIP,    // accept a skip or a length
39         ONEOF,  // accept one of a few values
40         SUBSETOF // accept a string composed of given characters
41 };
42
43
44 /// Listings package parameter information.
45 // FIXME: make this class visible outside of this file so that
46 // FIXME: it can be used directly in the frontend and in the LyX format
47 // FIXME: parsing.
48 class ListingsParam {
49 public:
50         /// Default ctor for STL containers.
51         ListingsParam(): onoff_(false), type_(ALL)
52         {}
53         /// Main ctor.
54         ListingsParam(string const & v, bool o, param_type t,
55                 string const & i, docstring const & h)
56                 : value_(v), onoff_(o), type_(t), info_(i), hint_(h)
57         {}
58         /// Validate a paramater.
59         /// \retval an empty string if \c par is valid.
60         /// \retval otherwise an explanation WRT to \c par invalidity.
61         docstring validate(string const & par) const;
62 private:
63         /// default value
64         string value_;
65 public:
66         /// for option with value "true", "false".
67         /// if onoff is true,
68         ///   "true":  option
69         ///   "false":
70         ///   "other": option="other"
71         /// onoff is false,
72         ///   "true":  option=true
73         ///   "false": option=false
74         // FIXME: this is public because of InsetListingParam::addParam()
75         bool onoff_;
76 private:
77         /// validator type.
78         /// ALL:
79         /// TRUEFALSE:
80         /// INTEGER:
81         /// LENGTH:
82         ///     info is ignored.
83         /// ONEOF
84         ///     info is a \n separated string with allowed values
85         /// SUBSETOF
86         ///     info is a string from which par is composed of
87         ///     (e.g. floatplacement can be one or more of *tbph)
88         param_type type_;
89         /// information which meaning depends on parameter type.
90         /// \sa type_
91         string info_;
92         /// a help message that is displayed in the gui.
93         docstring hint_;
94 };
95
96
97 char const * allowed_skips = "\\smallskipamount,\\medskipamount,\\bigskipamount";
98
99
100 docstring ListingsParam::validate(string const & par) const
101 {
102         bool unclosed = false;
103         string par2 = par;
104         // braces are allowed
105         if (prefixIs(par, "{") && suffixIs(par, "}") && !suffixIs(par, "\\}"))  
106                 par2 = par.substr(1, par.size() - 2);
107
108         // check for unmatched braces
109         int braces = 0;
110         for (size_t i = 0; i < par2.size(); ++i) {
111                 if (par2[i] == '{' && (i == 0 || par2[i-1] != '\\'))
112                         ++braces;
113                 else if (par2[i] == '}' && (i == 0 || par2[i-1] != '\\'))
114                         --braces;
115         }
116         unclosed = braces != 0;
117         
118         switch (type_) {
119
120         case ALL:
121                 if (par2.empty() && !onoff_) {
122                         if (!hint_.empty())
123                                 return hint_;
124                         else
125                                 return _("A value is expected.");
126                 }
127                 if (unclosed)
128                         return _("Unbalanced braces!");
129                 return docstring();
130
131         case TRUEFALSE:
132                 if (par2.empty() && !onoff_) {
133                         if (!hint_.empty())
134                                 return hint_;
135                         else
136                                 return _("Please specify true or false.");
137                 }
138                 if (par2 != "true" && par2 != "false")
139                         return _("Only true or false is allowed.");
140                 if (unclosed)
141                         return _("Unbalanced braces!");
142                 return docstring();
143
144         case INTEGER:
145                 if (!isStrInt(par2)) {
146                         if (!hint_.empty())
147                                 return hint_;
148                         else
149                                 return _("Please specify an integer value.");
150                 }
151                 if (convert<int>(par2) == 0 && par2[0] != '0')
152                         return _("An integer is expected.");
153                 if (unclosed)
154                         return _("Unbalanced braces!");
155                 return docstring();
156
157         case LENGTH:
158                 if (par2.empty() && !onoff_) {
159                         if (!hint_.empty())
160                                 return hint_;
161                         else
162                                 return _("Please specify a LaTeX length expression.");
163                 }
164                 if (!isValidLength(par2))
165                         return _("Invalid LaTeX length expression.");
166                 if (unclosed)
167                         return _("Unbalanced braces!");
168                 return docstring();
169
170         case SKIP:
171                 if (par2.empty() && !onoff_) {
172                         if (!hint_.empty())
173                                 return hint_;
174                         else
175                                 return bformat(_("Please specify a LaTeX length expression or a skip amount (%1$s)"),
176                                                from_ascii(subst(allowed_skips, ",", ", ")));
177                 }
178                 if (!isValidLength(par2) && tokenPos(allowed_skips, ',', par2) == -1)
179                         return _("Not a valid LaTeX length expression or skip amount.");
180                 if (unclosed)
181                         return _("Unbalanced braces!");
182                 return docstring();
183
184         case ONEOF: {
185                 if (par2.empty() && !onoff_) {
186                         if (!hint_.empty())
187                                 return hint_;
188                         else
189                                 return bformat(_("Please specify one of %1$s."),
190                                                            from_utf8(info_));
191                 }
192                 // break value to allowed strings
193                 vector<string> lists;
194                 string v;
195                 for (size_t i = 0; i != info_.size(); ++i) {
196                         if (info_[i] == '\n') {
197                                 lists.push_back(v);
198                                 v = string();
199                         } else
200                                 v += info_[i];
201                 }
202                 if (!v.empty())
203                         lists.push_back(v);
204
205                 // good, find the string
206                 if (find(lists.begin(), lists.end(), par2) != lists.end()) {
207                         if (unclosed)
208                                 return _("Unbalanced braces!");
209                         return docstring();
210                 }
211                 // otherwise, produce a meaningful error message.
212                 string matching_names;
213                 for (vector<string>::iterator it = lists.begin();
214                         it != lists.end(); ++it) {
215                         if (it->size() >= par2.size() && it->substr(0, par2.size()) == par2) {
216                                 if (matching_names.empty())
217                                         matching_names += *it;
218                                 else
219                                         matching_names += ", " + *it;
220                         }
221                 }
222                 if (matching_names.empty())
223                         return bformat(_("Try one of %1$s."), from_utf8(info_));
224                 else
225                         return bformat(_("I guess you mean %1$s."), from_utf8(matching_names));
226                 return docstring();
227         }
228         case SUBSETOF:
229                 if (par2.empty() && !onoff_) {
230                         if (!hint_.empty())
231                                 return hint_;
232                         else
233                                 return bformat(_("Please specify one or more of '%1$s'."),
234                                                            from_utf8(info_));
235                 }
236                 for (size_t i = 0; i < par2.size(); ++i)
237                         if (info_.find(par2[i], 0) == string::npos)
238                                 return bformat(_("Should be composed of one or more of %1$s."),
239                                                 from_utf8(info_));
240                 if (unclosed)
241                         return _("Unbalanced braces!");
242                 return docstring();
243         }
244         return docstring();
245 }
246
247
248 /// languages and language/dialect combinations
249 char const * allowed_languages =
250         "no language\nABAP\n[R/2 4.3]ABAP\n[R/2 5.0]ABAP\n[R/3 3.1]ABAP\n"
251         "[R/3 4.6C]ABAP\n[R/3 6.10]ABAP\nACSL\nAda\n[2005]Ada\n[83]Ada\n"
252         "[95]Ada\nALGOL\n[60]ALGOL\n[68]ALGOL\nAssembler\n"
253         "[Motorola68k]Assembler\n[x86masm]Assembler\nAwk\n[gnu]Awk\n[POSIX]Awk\n"
254         "bash\nBasic\n[Visual]Basic\nC\n[ANSI]C\n[Handel]C\n[Objective]C\n"
255         "[Sharp]C\nC++\n[ANSI]C++\n[GNU]C++\n[ISO]C++\n[Visual]C++\nCaml\n"
256         "[light]Caml\n[Objective]Caml\nClean\nCobol\n[1974]Cobol\n[1985]Cobol\n"
257         "[ibm]Cobol\nComal 80\ncommand.com\n[WinXP]command.com\nComsol\ncsh\n"
258         "Delphi\nEiffel\nElan\nerlang\nEuphoria\nFortran\n[77]Fortran\n[90]Fortran\n"
259         "[95]Fortran\nGCL\nGnuplot\nHaskell\nHTML\nIDL\n[CORBA]IDL\ninform\n"
260         "Java\n[AspectJ]Java\nJVMIS\nksh\nLingo\nLisp\n[Auto]Lisp\nLogo\n"
261         "make\n[gnu]make\nMathematica\n[1.0]Mathematica\n[3.0]Mathematica\n"
262         "[5.2]Mathematica\nMatlab\nMercury\nMetaPost\nMiranda\nMizar\nML\n"
263         "Modula-2\nMuPAD\nNASTRAN\nOberon-2\nOCL\n[decorative]OCL\n[OMG]OCL\n"
264         "Octave\nOz\nPascal\n[Borland6]Pascal\n[Standard]Pascal\n[XSC]Pascal\n"
265         "Perl\nPHP\nPL/I\nPlasm\nPostScript\nPOV\nProlog\nPromela\nPSTricks\n"
266         "Python\nR\nReduce\nRexx\nRSL\nRuby\nS\n[PLUS]S\nSAS\nScilab\nsh\n"
267         "SHELXL\nSimula\n[67]Simula\n[CII]Simula\n[DEC]Simula\n[IBM]Simula\n"
268         "SPARQL\nSQL\ntcl\n[tk]tcl\nTeX\n[AlLaTeX]TeX\n[common]TeX\n[LaTeX]TeX\n"
269         "[plain]TeX\n[primitive]TeX\nVBScript\nVerilog\nVHDL\n[AMS]VHDL\nVRML\n"
270         "[97]VRML\nXML\nXSLT";
271
272
273 /// ListingsParam Validator.
274 /// This class is aimed to be a singleton which is instantiated in
275 /// \c InsetListingsParams::addParam().
276 // FIXME: transfer this validator to the frontend.
277 // FIXME: avoid the use of exception.
278 class ParValidator
279 {
280 public:
281         ParValidator();
282
283         /// validate a parameter for a given name.
284         /// return an error message if \c par is an invalid parameter.
285         docstring validate(string const & name, string const & par) const;
286
287         /// return the onoff status of a parameter \c key, if \c key is not found
288         /// return false
289         bool onoff(string const & key) const;
290
291 private:
292         /// key is the name of the parameter
293         typedef map<string, ListingsParam> ListingsParams;
294         ListingsParams all_params_;
295 };
296
297
298 ParValidator::ParValidator()
299 {
300         docstring const empty_hint;
301         docstring const style_hint = _("Use \\footnotesize, \\small, \\itshape, "
302                 "\\ttfamily or something like that");
303         docstring const frame_hint = _("none, leftline, topline, bottomline, lines, "
304                 "single, shadowbox or subset of trblTRBL");
305         docstring const frameround_hint = _("Enter four letters (either t = round "
306                 "or f = square) for top right, bottom "
307                 "right, bottom left and top left corner.");
308         docstring const color_hint = _("Enter something like \\color{white}");
309
310         /// options copied from page 26 of listings manual
311         // FIXME: add default parameters ... (which is not used now)
312         all_params_["float"] =
313                 ListingsParam("false", true, SUBSETOF, "*tbph", empty_hint);
314         all_params_["floatplacement"] =
315                 ListingsParam("tbp", false, SUBSETOF, "tbp", empty_hint);
316         all_params_["aboveskip"] =
317                 ListingsParam("\\medskipamount", false, SKIP, "", empty_hint);
318         all_params_["belowskip"] =
319                 ListingsParam("\\medskipamount", false, SKIP, "", empty_hint);
320         all_params_["lineskip"] =
321                 ListingsParam("", false, SKIP, "", empty_hint);
322         all_params_["boxpos"] =
323                 ListingsParam("", false, SUBSETOF, "bct", empty_hint);
324         all_params_["print"] =
325                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
326         all_params_["firstline"] =
327                 ListingsParam("", false, INTEGER, "", empty_hint);
328         all_params_["lastline"] =
329                 ListingsParam("", false, INTEGER, "", empty_hint);
330         all_params_["linerange"] =
331                 ListingsParam("", false, ALL, "", empty_hint);
332         all_params_["showlines"] =
333                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
334         all_params_["emptylines"] =
335                 ListingsParam("", false, ALL, "", _(
336                 "Expect a number with an optional * before it"));
337         all_params_["gobble"] =
338                 ListingsParam("", false, INTEGER, "", empty_hint);
339         all_params_["style"] =
340                 ListingsParam("", false, ALL, "", empty_hint);
341         all_params_["language"] =
342                 ListingsParam("", false, ONEOF, allowed_languages, empty_hint);
343         all_params_["alsolanguage"] =
344                 ListingsParam("", false, ONEOF, allowed_languages, empty_hint);
345         all_params_["defaultdialect"] =
346                 ListingsParam("", false, ONEOF, allowed_languages, empty_hint);
347         all_params_["printpod"] =
348                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
349         all_params_["usekeywordsintag"] =
350                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
351         all_params_["tagstyle"] =
352                 ListingsParam("", false, ALL, "", style_hint);
353         all_params_["markfirstintag"] =
354                 ListingsParam("", false, ALL, "", style_hint);
355         all_params_["makemacrouse"] =
356                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
357         all_params_["basicstyle"] =
358                 ListingsParam("", false, ALL, "", style_hint);
359         all_params_["identifierstyle"] =
360                 ListingsParam("", false, ALL, "", style_hint);
361         all_params_["commentstyle"] =
362                 ListingsParam("", false, ALL, "", style_hint);
363         all_params_["stringstyle"] =
364                 ListingsParam("", false, ALL, "", style_hint);
365         all_params_["keywordstyle"] =
366                 ListingsParam("", false, ALL, "", style_hint);
367         all_params_["ndkeywordstyle"] =
368                 ListingsParam("", false, ALL, "", style_hint);
369         all_params_["classoffset"] =
370                 ListingsParam("", false, INTEGER, "", empty_hint);
371         all_params_["texcsstyle"] =
372                 ListingsParam("", false, ALL, "", style_hint);
373         all_params_["directivestyle"] =
374                 ListingsParam("", false, ALL, "", style_hint);
375         all_params_["emph"] =
376                 ListingsParam("", false, ALL, "", empty_hint);
377         all_params_["moreemph"] =
378                 ListingsParam("", false, ALL, "", empty_hint);
379         all_params_["deleteemph"] =
380                 ListingsParam("", false, ALL, "", empty_hint);
381         all_params_["emphstyle"] =
382                 ListingsParam("", false, ALL, "", empty_hint);
383         all_params_["delim"] =
384                 ListingsParam("", false, ALL, "", empty_hint);
385         all_params_["moredelim"] =
386                 ListingsParam("", false, ALL, "", empty_hint);
387         all_params_["deletedelim"] =
388                 ListingsParam("", false, ALL, "", empty_hint);
389         all_params_["extendedchars"] =
390                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
391         all_params_["inputencoding"] =
392                 ListingsParam("", false, ALL, "", empty_hint);
393         all_params_["upquote"] =
394                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
395         all_params_["tabsize"] =
396                 ListingsParam("", false, INTEGER, "", empty_hint);
397         all_params_["showtabs"] =
398                 ListingsParam("", false, ALL, "", empty_hint);
399         all_params_["tab"] =
400                 ListingsParam("", false, ALL, "", empty_hint);
401         all_params_["showspaces"] =
402                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
403         all_params_["showstringspaces"] =
404                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
405         all_params_["formfeed"] =
406                 ListingsParam("", false, ALL, "", empty_hint);
407         all_params_["numbers"] =
408                 ListingsParam("", false, ONEOF, "none\nleft\nright", empty_hint);
409         all_params_["stepnumber"] =
410                 ListingsParam("", false, INTEGER, "", empty_hint);
411         all_params_["numberfirstline"] =
412                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
413         all_params_["numberstyle"] =
414                 ListingsParam("", false, ALL, "", style_hint);
415         all_params_["numbersep"] =
416                 ListingsParam("", false, LENGTH, "", empty_hint);
417         all_params_["numberblanklines"] =
418                 ListingsParam("", false, ALL, "", empty_hint);
419         all_params_["firstnumber"] =
420                 ListingsParam("", false, ALL, "", _("auto, last or a number"));
421         all_params_["name"] =
422                 ListingsParam("", false, ALL, "", empty_hint);
423         all_params_["thelstnumber"] =
424                 ListingsParam("", false, ALL, "", empty_hint);
425         all_params_["title"] =
426                 ListingsParam("", false, ALL, "", empty_hint);
427         // this option is not handled in the parameter box
428         all_params_["caption"] =
429                 ListingsParam("", false, ALL, "", _(
430                 "This parameter should not be entered here. Please use the caption "
431                 "edit box (when using the child document dialog) or "
432                 "menu Insert->Caption (when defining a listing inset)"));
433         // this option is not handled in the parameter box
434         all_params_["label"] =
435                 ListingsParam("", false, ALL, "",_(
436                 "This parameter should not be entered here. Please use the label "
437                 "edit box (when using the child document dialog) or "
438                 "menu Insert->Label (when defining a listing inset)"));
439         all_params_["nolol"] =
440                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
441         all_params_["captionpos"] =
442                 ListingsParam("", false, SUBSETOF, "tb", empty_hint);
443         all_params_["abovecaptionskip"] =
444                 ListingsParam("", false, SKIP, "", empty_hint);
445         all_params_["belowcaptionskip"] =
446                 ListingsParam("", false, SKIP, "", empty_hint);
447         all_params_["linewidth"] =
448                 ListingsParam("", false, LENGTH, "", empty_hint);
449         all_params_["xleftmargin"] =
450                 ListingsParam("", false, LENGTH, "", empty_hint);
451         all_params_["xrightmargin"] =
452                 ListingsParam("", false, LENGTH, "", empty_hint);
453         all_params_["resetmargins"] =
454                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
455         all_params_["breaklines"] =
456                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
457         all_params_["breakatwhitespace"] =
458                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
459         all_params_["prebreak"] =
460                 ListingsParam("", false, ALL, "", empty_hint);
461         all_params_["postbreak"] =
462                 ListingsParam("", false, ALL, "", empty_hint);
463         all_params_["breakindent"] =
464                 ListingsParam("", false, LENGTH, "", empty_hint);
465         all_params_["breakautoindent"] =
466                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
467         all_params_["frame"] =
468                 ListingsParam("", false, ALL, "", frame_hint);
469         all_params_["frameround"] =
470                 ListingsParam("", false, SUBSETOF, "tf", frameround_hint);
471         all_params_["framesep"] =
472                 ListingsParam("", false, LENGTH, "", empty_hint);
473         all_params_["rulesep"] =
474                 ListingsParam("", false, LENGTH, "", empty_hint);
475         all_params_["framerule"] =
476                 ListingsParam("", false, LENGTH, "", empty_hint);
477         all_params_["framexleftmargin"] =
478                 ListingsParam("", false, LENGTH, "", empty_hint);
479         all_params_["framexrightmargin"] =
480                 ListingsParam("", false, LENGTH, "", empty_hint);
481         all_params_["framextopmargin"] =
482                 ListingsParam("", false, LENGTH, "", empty_hint);
483         all_params_["framexbottommargin"] =
484                 ListingsParam("", false, LENGTH, "", empty_hint);
485         all_params_["backgroundcolor"] =
486                 ListingsParam("", false, ALL, "", color_hint );
487         all_params_["rulecolor"] =
488                 ListingsParam("", false, ALL, "", color_hint );
489         all_params_["fillcolor"] =
490                 ListingsParam("", false, ALL, "", color_hint );
491         all_params_["rulesepcolor"] =
492                 ListingsParam("", false, ALL, "", color_hint );
493         all_params_["frameshape"] =
494                 ListingsParam("", false, ALL, "", empty_hint);
495         all_params_["index"] =
496                 ListingsParam("", false, ALL, "", empty_hint);
497         all_params_["moreindex"] =
498                 ListingsParam("", false, ALL, "", empty_hint);
499         all_params_["deleteindex"] =
500                 ListingsParam("", false, ALL, "", empty_hint);
501         all_params_["indexstyle"] =
502                 ListingsParam("", false, ALL, "", empty_hint);
503         all_params_["columns"] =
504                 ListingsParam("", false, ALL, "", empty_hint);
505         all_params_["flexiblecolumns"] =
506                 ListingsParam("", false, ALL, "", empty_hint);
507         all_params_["keepspaces"] =
508                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
509         all_params_["basewidth"] =
510                 ListingsParam("", false, LENGTH, "", empty_hint);
511         all_params_["fontadjust"] =
512                 ListingsParam("", true, TRUEFALSE, "", empty_hint);
513         all_params_["texcl"] =
514                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
515         all_params_["mathescape"] =
516                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
517         all_params_["escapechar"] =
518                 ListingsParam("", false, ALL, "", empty_hint);
519         all_params_["escapeinside"] =
520                 ListingsParam("", false, ALL, "", empty_hint);
521         all_params_["escapebegin"] =
522                 ListingsParam("", false, ALL, "", empty_hint);
523         all_params_["escapeend"] =
524                 ListingsParam("", false, ALL, "", empty_hint);
525         all_params_["fancyvrb"] =
526                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
527         all_params_["fvcmdparams"] =
528                 ListingsParam("", false, ALL, "", empty_hint);
529         all_params_["morefvcmdparams"] =
530                 ListingsParam("", false, ALL, "", empty_hint);
531         all_params_["keywordsprefix"] =
532                 ListingsParam("", false, ALL, "", empty_hint);
533         all_params_["keywords"] =
534                 ListingsParam("", false, ALL, "", empty_hint);
535         all_params_["morekeywords"] =
536                 ListingsParam("", false, ALL, "", empty_hint);
537         all_params_["deletekeywords"] =
538                 ListingsParam("", false, ALL, "", empty_hint);
539         all_params_["ndkeywords"] =
540                 ListingsParam("", false, ALL, "", empty_hint);
541         all_params_["morendkeywords"] =
542                 ListingsParam("", false, ALL, "", empty_hint);
543         all_params_["deletendkeywords"] =
544                 ListingsParam("", false, ALL, "", empty_hint);
545         all_params_["texcs"] =
546                 ListingsParam("", false, ALL, "", empty_hint);
547         all_params_["moretexcs"] =
548                 ListingsParam("", false, ALL, "", empty_hint);
549         all_params_["deletetexcs"] =
550                 ListingsParam("", false, ALL, "", empty_hint);
551         all_params_["directives"] =
552                 ListingsParam("", false, ALL, "", empty_hint);
553         all_params_["moredirectives"] =
554                 ListingsParam("", false, ALL, "", empty_hint);
555         all_params_["deletedirectives"] =
556                 ListingsParam("", false, ALL, "", empty_hint);
557         all_params_["sensitive"] =
558                 ListingsParam("", false, ALL, "", empty_hint);
559         all_params_["alsoletter"] =
560                 ListingsParam("", false, ALL, "", empty_hint);
561         all_params_["alsodigit"] =
562                 ListingsParam("", false, ALL, "", empty_hint);
563         all_params_["alsoother"] =
564                 ListingsParam("", false, ALL, "", empty_hint);
565         all_params_["otherkeywords"] =
566                 ListingsParam("", false, ALL, "", empty_hint);
567         all_params_["tag"] =
568                 ListingsParam("", false, ALL, "", empty_hint);
569         all_params_["string"] =
570                 ListingsParam("", false, ALL, "", empty_hint);
571         all_params_["morestring"] =
572                 ListingsParam("", false, ALL, "", empty_hint);
573         all_params_["deletestring"] =
574                 ListingsParam("", false, ALL, "", empty_hint);
575         all_params_["comment"] =
576                 ListingsParam("", false, ALL, "", empty_hint);
577         all_params_["morecomment"] =
578                 ListingsParam("", false, ALL, "", empty_hint);
579         all_params_["deletecomment"] =
580                 ListingsParam("", false, ALL, "", empty_hint);
581         all_params_["keywordcomment"] =
582                 ListingsParam("", false, ALL, "", empty_hint);
583         all_params_["morekeywordcomment"] =
584                 ListingsParam("", false, ALL, "", empty_hint);
585         all_params_["deletekeywordcomment"] =
586                 ListingsParam("", false, ALL, "", empty_hint);
587         all_params_["keywordcommentsemicolon"] =
588                 ListingsParam("", false, ALL, "", empty_hint);
589         all_params_["podcomment"] =
590                 ListingsParam("", false, ALL, "", empty_hint);
591         // the following are experimental listings features
592         all_params_["procnamekeys"] =
593                 ListingsParam("", false, ALL, "", empty_hint);
594         all_params_["moreprocnamekeys"] =
595                 ListingsParam("", false, ALL, "", empty_hint);
596         all_params_["deleteprocnamekeys"] =
597                 ListingsParam("", false, ALL, "", empty_hint);
598         all_params_["procnamestyle"] =
599                 ListingsParam("", false, ALL, "", style_hint);
600         all_params_["indexprocnames"] =
601                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
602         all_params_["hyperref"] =
603                 ListingsParam("", false, ALL, "", empty_hint);
604         all_params_["morehyperref"] =
605                 ListingsParam("", false, ALL, "", empty_hint);
606         all_params_["deletehyperref"] =
607                 ListingsParam("", false, ALL, "", empty_hint);
608         all_params_["hyperanchor"] =
609                 ListingsParam("", false, ALL, "", empty_hint);
610         all_params_["hyperlink"] =
611                 ListingsParam("", false, ALL, "", empty_hint);
612         all_params_["literate"] =
613                 ListingsParam("", false, ALL, "", empty_hint);
614         all_params_["lgrindef"] =
615                 ListingsParam("", false, ALL, "", empty_hint);
616         all_params_["rangebeginprefix"] =
617                 ListingsParam("", false, ALL, "", empty_hint);
618         all_params_["rangebeginsuffix"] =
619                 ListingsParam("", false, ALL, "", empty_hint);
620         all_params_["rangeendprefix"] =
621                 ListingsParam("", false, ALL, "", empty_hint);
622         all_params_["rangeendsuffix"] =
623                 ListingsParam("", false, ALL, "", empty_hint);
624         all_params_["rangeprefix"] =
625                 ListingsParam("", false, ALL, "", empty_hint);
626         all_params_["rangesuffix"] =
627                 ListingsParam("", false, ALL, "", empty_hint);
628         all_params_["includerangemarker"] =
629                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
630         all_params_["multicols"] =
631                 ListingsParam("", false, INTEGER, "", empty_hint);
632 }
633
634
635 docstring ParValidator::validate(string const & name,
636                 string const & par) const
637 {
638         if (name.empty())
639                 return _("Invalid (empty) listing parameter name.");
640
641         if (name[0] == '?') {
642                 string suffix = trim(string(name, 1));
643                 string param_names;
644                 ListingsParams::const_iterator it = all_params_.begin();
645                 ListingsParams::const_iterator end = all_params_.end();
646                 for (; it != end; ++it) {
647                         if (suffix.empty() || contains(it->first, suffix)) {
648                                 if (!param_names.empty())
649                                         param_names += ", ";
650                                 param_names += it->first;
651                         }
652                 }
653                 if (suffix.empty())
654                         return bformat(
655                                         _("Available listing parameters are %1$s"), from_ascii(param_names));
656                 else
657                         return bformat(
658                                         _("Available listings parameters containing string \"%1$s\" are %2$s"), 
659                                                 from_utf8(suffix), from_utf8(param_names));
660         }
661  
662         // locate name in parameter table
663         ListingsParams::const_iterator it = all_params_.find(name);
664         if (it != all_params_.end()) {
665                 docstring msg = it->second.validate(par);
666                 if (msg.empty())
667                         return msg;
668                 else
669                         return bformat(_("Parameter %1$s: "), from_utf8(name)) + msg;
670         } else {
671                 // otherwise, produce a meaningful error message.
672                 string matching_names;
673                 ListingsParams::const_iterator end = all_params_.end();
674                 for (it = all_params_.begin(); it != end; ++it) {
675                         if (prefixIs(it->first, name)) {
676                                 if (!matching_names.empty())
677                                         matching_names += ", ";
678                                 matching_names += it->first;
679                         }
680                 }
681                 if (matching_names.empty())
682                         return bformat(_("Unknown listing parameter name: %1$s"),
683                                                                 from_utf8(name));
684                 else
685                         return bformat(_("Parameters starting with '%1$s': %2$s"),
686                                                                 from_utf8(name), from_utf8(matching_names));
687         }
688         return docstring();
689 }
690
691
692 bool ParValidator::onoff(string const & name) const
693 {
694         // locate name in parameter table
695         ListingsParams::const_iterator it = all_params_.find(name);
696         if (it != all_params_.end())
697                 return it->second.onoff_;
698         else
699                 return false;
700 }
701
702 } // namespace anon.
703
704 // define a global ParValidator
705 ParValidator * par_validator = 0;
706
707 InsetListingsParams::InsetListingsParams()
708         : inline_(false), params_(), status_(InsetCollapsable::Open)
709 {
710 }
711
712
713 InsetListingsParams::InsetListingsParams(string const & par, bool in,
714                 InsetCollapsable::CollapseStatus s)
715         : inline_(in), params_(), status_(s)
716 {
717         // this will activate parameter validation.
718         fromEncodedString(par);
719 }
720
721
722 void InsetListingsParams::write(ostream & os) const
723 {
724         if (inline_)
725                 os << "true ";
726         else
727                 os << "false ";
728         os << status_ << " \""  << encodedString() << "\"";
729 }
730
731
732 void InsetListingsParams::read(Lexer & lex)
733 {
734         lex >> inline_;
735         int s = InsetCollapsable::Collapsed;
736         lex >> s;
737         status_ = static_cast<InsetCollapsable::CollapseStatus>(s);
738         string par;
739         lex >> par;
740         fromEncodedString(par);
741 }
742
743
744 string InsetListingsParams::params(string const & sep) const
745 {
746         string par;
747         keyValuePair::const_iterator it = params_.begin();
748         for (; it != params_.end(); ++it) {
749                 if (!par.empty())
750                         par += sep;
751                 // key=value,key=value1 is stored in params_ as key=value,key_=value1.
752                 if (it->second.empty())
753                         par += rtrim(it->first, "_");
754                 else
755                         par += rtrim(it->first, "_") + '=' + it->second;
756         }
757         return par;
758 }
759
760
761 bool InsetListingsParams::hasParam(string const & key) const
762 {
763         keyValuePair::const_iterator it = params_.begin();
764         for (; it != params_.end(); ++it) {
765                 if (it->first == key)
766                         return true;
767         }
768         return false;
769 }
770
771
772 string InsetListingsParams::getValue(string const & key) const
773 {
774         keyValuePair::const_iterator it = params_.begin();
775         for (; it != params_.end(); ++it) {
776                 if (it->first == key)
777                         return it->second;
778         }
779         return string();
780 }
781
782
783 void InsetListingsParams::addParam(string const & key, 
784                 string const & value, bool replace)
785 {
786         if (key.empty())
787                 return;
788
789         // duplicate parameters!
790         string keyname = key;
791         if (!replace && hasParam(key))
792                 // key=value,key=value1 is allowed in listings
793                 // use key_, key__, key___ etc to avoid name conflict
794                 while (hasParam(keyname += '_')) { }
795         // check onoff flag
796         // onoff parameter with value false
797         if (!par_validator)
798                 par_validator = new ParValidator;
799         if (par_validator->onoff(key) && (value == "false" || value == "{false}"))
800                 params_.push_back(make_pair(keyname, string()));
801         // if the parameter is surrounded with {}, good
802         else if (prefixIs(value, "{") && suffixIs(value, "}"))
803                 params_.push_back(make_pair(keyname, value));
804         // otherwise, check if {} is needed. Add {} to all values with
805         // non-ascii/number characters, just to be safe
806         else {
807                 bool has_special_char = false;
808                 for (size_t i = 0; i < value.size(); ++i)
809                         if (!isAlnumASCII(value[i])) {
810                                 has_special_char = true;
811                                 break;
812                         }
813                 if (has_special_char)
814                         params_.push_back(make_pair(keyname, "{" + value + "}"));
815                 else
816                         params_.push_back(make_pair(keyname, value));
817         }
818 }
819
820
821 void InsetListingsParams::addParams(string const & par)
822 {
823         string key;
824         string value;
825         bool isValue = false;
826         int braces = 0;
827         for (size_t i = 0; i < par.size(); ++i) {
828                 // end of par
829                 if (par[i] == '\n') {
830                         addParam(trim(key), trim(value));
831                         key = string();
832                         value = string();
833                         isValue = false;
834                         continue;
835                 } else if (par[i] == ',' && braces == 0) {
836                         addParam(trim(key), trim(value));
837                         key = string();
838                         value = string();
839                         isValue = false;
840                         continue;
841                 } else if (par[i] == '=' && braces == 0) {
842                         isValue = true;
843                         continue;
844                 } else if (par[i] == '{' && i > 0 && par[i-1] != '\\')
845                         // don't count a brace in first position
846                         ++braces;
847                 else if (par[i] == '}' && i != par.size() - 1 
848                          && (i == 0 || (i > 0 && par[i-1] != '\\')))
849                         --braces;
850
851                 if (isValue)
852                         value += par[i];
853                 else
854                         key += par[i];
855         }
856         if (!trim(key).empty())
857                 addParam(trim(key), trim(value));
858 }
859
860
861 void InsetListingsParams::setParams(string const & par)
862 {
863         params_.clear();
864         addParams(par);
865 }
866
867
868 string InsetListingsParams::encodedString() const
869 {
870         // Encode string!
871         // '"' is handled differently because it will
872         // terminate a lyx token.
873         string par = params();
874         // '"' is now &quot;  ==> '"' is now &amp;quot;
875         par = subst(par, "&", "&amp;");
876         // '"' is now &amp;quot; ==> '&quot;' is now &amp;quot;
877         par = subst(par, "\"", "&quot;");
878         return par;
879 }
880
881
882 string InsetListingsParams::separatedParams(bool keepComma) const
883 {
884         if (keepComma)
885                 return params(",\n");
886         else
887                 return params("\n");
888 }
889
890
891 void InsetListingsParams::fromEncodedString(string const & in)
892 {
893         // Decode string! Reversal of encodedString
894         string par = in;
895         // '&quot;' is now &amp;quot; ==> '"' is now &amp;quot;
896         par = subst(par, "&quot;", "\"");
897         //  '"' is now &amp;quot; ==> '"' is now &quot;
898         par = subst(par, "&amp;", "&");
899         setParams(par);
900 }
901
902
903 bool InsetListingsParams::isFloat() const
904 {
905         return hasParam("float");
906 }
907
908
909 string InsetListingsParams::getParamValue(string const & param) const
910 {
911         string par = getValue(param);
912         if (prefixIs(par, "{") && suffixIs(par, "}"))
913                 return par.substr(1, par.size() - 2);
914         else
915                 return par;
916 }
917
918
919 docstring InsetListingsParams::validate() const
920 {
921         docstring msg;
922         if (!par_validator)
923                 par_validator = new ParValidator;
924         // return msg for first key=value pair which is incomplete or has an error
925         keyValuePair::const_iterator it = params_.begin();
926         for (; it != params_.end(); ++it) {
927                 // key trimmed
928                 msg = par_validator->validate(rtrim(it->first, "_"), it->second);
929                 if (!msg.empty())
930                         return msg;
931         }
932         return msg;
933 }
934
935 } // namespace lyx