]> git.lyx.org Git - features.git/blob - src/insets/InsetListingsParams.cpp
Allow prefixing a listings parameter with @ to bypass validation, useful when new...
[features.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
13 #include "InsetListingsParams.h"
14
15 #include "gettext.h"
16 #include "Length.h"
17 #include "Lexer.h"
18
19 #include "support/lstrings.h"
20 #include "support/textutils.h"
21 #include "support/convert.h"
22
23 #include <boost/assert.hpp>
24
25 #include <sstream>
26
27 using std::map;
28 using std::vector;
29 using std::ostream;
30 using std::string;
31 using std::exception;
32
33 namespace lyx
34 {
35
36 using support::bformat;
37 using support::trim;
38 using support::ltrim;
39 using support::rtrim;
40 using support::subst;
41 using support::isStrInt;
42 using support::prefixIs;
43 using support::suffixIs;
44 using support::getVectorFromString;
45 using lyx::support::contains;
46
47 namespace {
48
49 enum param_type {
50         ALL,  // accept all
51         TRUEFALSE, // accept 'true' or 'false'
52         INTEGER, // accept an integer
53         LENGTH,  // accept a latex length
54         ONEOF,  // accept one of a few values
55         SUBSETOF, // accept a string composed of given characters
56 };
57
58
59 /// Listings package parameter information.
60 // FIXME: make this class visible outside of this file so that
61 // FIXME: it can be used directly in the frontend and in the LyX format
62 // FIXME: parsing.
63 class ListingsParam {
64 public:
65         /// Default ctor for STL containers.
66         ListingsParam(): onoff_(false), type_(ALL)
67         {}
68         /// Main ctor.
69         ListingsParam(string const & v, bool o, param_type t,
70                 string const & i, docstring const & h)
71                 : value_(v), onoff_(o), type_(t), info_(i), hint_(h)
72         {}
73         /// Validate a paramater.
74         /// \retval an empty string if \c par is valid.
75         /// \retval otherwise an explanation WRT to \c par invalidity.
76         docstring validate(string const & par) const;
77 private:
78         /// default value
79         string value_;
80 public:
81         /// for option with value "true", "false".
82         /// if onoff is true,
83         ///   "true":  option
84         ///   "false":
85         ///   "other": option="other"
86         /// onoff is false,
87         ///   "true":  option=true
88         ///   "false": option=false
89         // FIXME: this is public because of InsetListingParam::addParam()
90         bool onoff_;
91 private:
92         /// validator type.
93         /// ALL:
94         /// TRUEFALSE:
95         /// INTEGER:
96         /// LENGTH:
97         ///     info is ignored.
98         /// ONEOF
99         ///     info is a \n separated string with allowed values
100         /// SUBSETOF
101         ///     info is a string from which par is composed of
102         ///     (e.g. floatplacement can be one or more of *tbph)
103         param_type type_;
104         /// information which meaning depends on parameter type.
105         /// \sa type_
106         string info_;
107         /// a help message that is displayed in the gui.
108         docstring hint_;
109 };
110
111
112 docstring ListingsParam::validate(string const & par) const
113 {
114         bool unclosed = false;
115         string par2 = par;
116         // braces are allowed
117         if (prefixIs(par, "{") && suffixIs(par, "}"))
118                 par2 = par.substr(1, par.size() - 2);
119         else if (prefixIs(par, "{")) {
120                 par2 = par.substr(1);
121                 unclosed = true;
122         }
123
124         switch (type_) {
125
126         case ALL:
127                 if (par2.empty() && !onoff_ && hint_ != _("Bypass validation")) {
128                         if (!hint_.empty())
129                                 return hint_;
130                         else
131                                 return _("A value is expected.");
132                 }
133                 if (unclosed)
134                                 return _("Unbalanced braces!");
135                 return docstring();
136
137         case TRUEFALSE:
138                 if (par2.empty() && !onoff_) {
139                         if (!hint_.empty())
140                                 return hint_;
141                         else
142                                 return _("Please specify true or false.");
143                 }
144                 if (par2 != "true" && par2 != "false")
145                         return _("Only true or false is allowed.");
146                 if (unclosed)
147                         return _("Unbalanced braces!");
148                 return docstring();
149
150         case INTEGER:
151                 if (!isStrInt(par2)) {
152                         if (!hint_.empty())
153                                 return hint_;
154                         else
155                                 return _("Please specify an integer value.");
156                 }
157                 if (convert<int>(par2) == 0 && par2[0] != '0')
158                         return _("An integer is expected.");
159                 if (unclosed)
160                         return _("Unbalanced braces!");
161                 return docstring();
162
163         case LENGTH:
164                 if (par2.empty() && !onoff_) {
165                         if (!hint_.empty())
166                                 return hint_;
167                         else
168                                 return _("Please specify a LaTeX length expression.");
169                 }
170                 if (!isValidLength(par2))
171                         return _("Invalid LaTeX length expression.");
172                 if (unclosed)
173                         return _("Unbalanced braces!");
174                 return docstring();
175
176         case ONEOF: {
177                 if (par2.empty() && !onoff_) {
178                         if (!hint_.empty())
179                                 return hint_;
180                         else
181                                 return bformat(_("Please specify one of %1$s."),
182                                                            from_utf8(info_));
183                 }
184                 // break value to allowed strings
185                 vector<string> lists;
186                 string v;
187                 for (size_t i = 0; i != info_.size(); ++i) {
188                         if (info_[i] == '\n') {
189                                 lists.push_back(v);
190                                 v = string();
191                         } else
192                                 v += info_[i];
193                 }
194                 if (!v.empty())
195                         lists.push_back(v);
196
197                 // good, find the string
198                 if (std::find(lists.begin(), lists.end(), par2) != lists.end()) {
199                         if (unclosed)
200                                 return _("Unbalanced braces!");
201                         return docstring();
202                 }
203                 // otherwise, produce a meaningful error message.
204                 string matching_names;
205                 for (vector<string>::iterator it = lists.begin();
206                         it != lists.end(); ++it) {
207                         if (it->size() >= par2.size() && it->substr(0, par2.size()) == par2) {
208                                 if (matching_names.empty())
209                                         matching_names += *it;
210                                 else
211                                         matching_names += ", " + *it;
212                         }
213                 }
214                 if (matching_names.empty())
215                         return bformat(_("Try one of %1$s."), from_utf8(info_));
216                 else
217                         return bformat(_("I guess you mean %1$s."), from_utf8(matching_names));
218                 return docstring();
219         }
220         case SUBSETOF:
221                 if (par2.empty() && !onoff_) {
222                         if (!hint_.empty())
223                                 return hint_;
224                         else
225                                 return bformat(_("Please specify one or more of '%1$s'."),
226                                                            from_utf8(info_));
227                 }
228                 for (size_t i = 0; i < par2.size(); ++i)
229                         if (info_.find(par2[i], 0) == string::npos)
230                                 return bformat(_("Should be composed of one or more of %1$s."),
231                                                 from_utf8(info_));
232                 if (unclosed)
233                         return _("Unbalanced braces!");
234                 return docstring();
235         }
236         return docstring();
237 }
238
239
240 /// languages and language/dialect combinations
241 char const * allowed_languages =
242         "no language\nABAP\n[R/2 4.3]ABAP\n[R/2 5.0]ABAP\n[R/3 3.1]ABAP\n"
243         "[R/3 4.6C]ABAP\n[R/3 6.10]ABAP\nACSL\nAda\n[2005]Ada\n[83]Ada\n"
244         "[95]Ada\nALGOL\n[60]ALGOL\n[68]ALGOL\nAssembler\n"
245         "[Motorola68k]Assembler\n[x86masm]Assembler\nAwk\n[gnu]Awk\n[POSIX]Awk\n"
246         "bash\nBasic\n[Visual]Basic\nC\n[ANSI]C\n[Handel]C\n[Objective]C\n"
247         "[Sharp]C\nC++\n[ANSI]C++\n[GNU]C++\n[ISO]C++\n[Visual]C++\nCaml\n"
248         "[light]Caml\n[Objective]Caml\nClean\nCobol\n[1974]Cobol\n[1985]Cobol\n"
249         "[ibm]Cobol\nComal 80\ncommand.com\n[WinXP]command.com\nComsol\ncsh\n"
250         "Delphi\nEiffel\nElan\nEuphoria\nFortran\n[77]Fortran\n[90]Fortran\n"
251         "[95]Fortran\nGCL\nGnuplot\nHaskell\nHTML\nIDL\n[CORBA]IDL\ninform\n"
252         "Java\n[AspectJ]Java\nJVMIS\nksh\nLingo\nLisp\n[Auto]Lisp\nLogo\n"
253         "make\n[gnu]make\nMathematica\n[1.0]Mathematica\n[3.0]Mathematica\n"
254         "[5.2]Mathematica\nMatlab\nMercury\nMetaPost\nMiranda\nMizar\nML\n"
255         "Modula-2\nMuPAD\nNASTRAN\nOberon-2\nOCL\n[decorative]OCL\n[OMG]OCL\n"
256         "Octave\nOz\nPascal\n[Borland6]Pascal\n[Standard]Pascal\n[XSC]Pascal\n"
257         "Perl\nPHP\nPL/I\nPlasm\nPostScript\nPOV\nProlog\nPromela\nPSTricks\n"
258         "Python\nR\nReduce\nRexx\nRSL\nRuby\nS\n[PLUS]S\nSAS\nScilab\nsh\n"
259         "SHELXL\nSimula\n[67]Simula\n[CII]Simula\n[DEC]Simula\n[IBM]Simula\n"
260         "SPARQL\nSQL\ntcl\n[tk]tcl\nTeX\n[AlLaTeX]TeX\n[common]TeX\n[LaTeX]TeX\n"
261         "[plain]TeX\n[primitive]TeX\nVBScript\nVerilog\nVHDL\n[AMS]VHDL\nVRML\n"
262         "[97]VRML\nXML\nXSLT";
263
264
265 /// ListingsParam Validator.
266 /// This class is aimed to be a singleton which is instantiated in
267 /// \c InsetListingsParams::addParam().
268 // FIXME: transfer this validator to the frontend.
269 // FIXME: avoid the use of exception.
270 class ParValidator
271 {
272 public:
273         ParValidator();
274
275         /// \return the associated \c ListingsParam.
276         /// \warning an \c invalidParamexception will be thrown
277         ///          if the key is not found.
278         ListingsParam const & param(string const & key) const;
279
280         /// validate a parameter for a given key.
281         /// \warning an \c invalidParam exception will be thrown if
282         /// \c par is an invalid parameter.
283         ListingsParam const & validate(string const & key, string const & par) const;
284
285 private:
286         /// key is the name of the parameter
287         typedef map<string, ListingsParam> ListingsParams;
288         ListingsParams all_params_;
289 };
290
291
292 ParValidator::ParValidator()
293 {
294         docstring const empty_hint;
295         docstring const style_hint = _("Use \\footnotesize, \\small, \\itshape, "
296                 "\\ttfamily or something like that");
297         docstring const frame_hint = _("none, leftline, topline, bottomline, lines, "
298                 "single, shadowbox or subset of trblTRBL");
299         docstring const frameround_hint = _("Enter four letters (either t = round "
300                 "or f = square) for top right, bottom "
301                 "right, bottom left and top left corner.");
302         docstring const color_hint = _("Enter something like \\color{white}");
303
304         /// options copied from page 26 of listings manual
305         // FIXME: add default parameters ... (which is not used now)
306
307         // special ListingsParam returned for parameters starting with @
308         // which helps them bypass validation.
309         all_params_["@"] =
310                 ListingsParam("", false, ALL, "", _("Bypass validation"));
311
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, LENGTH, "", empty_hint);
318         all_params_["belowskip"] =
319                 ListingsParam("\\medskipamount", false, LENGTH, "", empty_hint);
320         all_params_["lineskip"] =
321                 ListingsParam("", false, LENGTH, "", 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, LENGTH, "", empty_hint);
445         all_params_["belowcaptionskip"] =
446                 ListingsParam("", false, LENGTH, "", 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_["prebreak"] =
458                 ListingsParam("", false, ALL, "", empty_hint);
459         all_params_["postbreak"] =
460                 ListingsParam("", false, ALL, "", empty_hint);
461         all_params_["breakindent"] =
462                 ListingsParam("", false, LENGTH, "", empty_hint);
463         all_params_["breakautoindent"] =
464                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
465         all_params_["frame"] =
466                 ListingsParam("", false, ALL, "", frame_hint);
467         all_params_["frameround"] =
468                 ListingsParam("", false, SUBSETOF, "tf", frameround_hint);
469         all_params_["framesep"] =
470                 ListingsParam("", false, LENGTH, "", empty_hint);
471         all_params_["rulesep"] =
472                 ListingsParam("", false, LENGTH, "", empty_hint);
473         all_params_["framerule"] =
474                 ListingsParam("", false, LENGTH, "", empty_hint);
475         all_params_["framexleftmargin"] =
476                 ListingsParam("", false, LENGTH, "", empty_hint);
477         all_params_["framexrightmargin"] =
478                 ListingsParam("", false, LENGTH, "", empty_hint);
479         all_params_["framextopmargin"] =
480                 ListingsParam("", false, LENGTH, "", empty_hint);
481         all_params_["framexbottommargin"] =
482                 ListingsParam("", false, LENGTH, "", empty_hint);
483         all_params_["backgroundcolor"] =
484                 ListingsParam("", false, ALL, "", color_hint );
485         all_params_["rulecolor"] =
486                 ListingsParam("", false, ALL, "", color_hint );
487         all_params_["fillcolor"] =
488                 ListingsParam("", false, ALL, "", color_hint );
489         all_params_["rulesepcolor"] =
490                 ListingsParam("", false, ALL, "", color_hint );
491         all_params_["frameshape"] =
492                 ListingsParam("", false, ALL, "", empty_hint);
493         all_params_["index"] =
494                 ListingsParam("", false, ALL, "", empty_hint);
495         all_params_["moreindex"] =
496                 ListingsParam("", false, ALL, "", empty_hint);
497         all_params_["deleteindex"] =
498                 ListingsParam("", false, ALL, "", empty_hint);
499         all_params_["indexstyle"] =
500                 ListingsParam("", false, ALL, "", empty_hint);
501         all_params_["columns"] =
502                 ListingsParam("", false, ALL, "", empty_hint);
503         all_params_["flexiblecolumns"] =
504                 ListingsParam("", false, ALL, "", empty_hint);
505         all_params_["keepspaces"] =
506                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
507         all_params_["basewidth"] =
508                 ListingsParam("", false, LENGTH, "", empty_hint);
509         all_params_["fontadjust"] =
510                 ListingsParam("", true, TRUEFALSE, "", empty_hint);
511         all_params_["texcl"] =
512                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
513         all_params_["mathescape"] =
514                 ListingsParam("", false, TRUEFALSE, "", empty_hint);
515         all_params_["escapechar"] =
516                 ListingsParam("", false, ALL, "", empty_hint);
517         all_params_["escapeinside"] =
518                 ListingsParam("", false, ALL, "", empty_hint);
519         all_params_["escepeinside"] =
520                 ListingsParam("", false, ALL, "", empty_hint);
521         all_params_["escepebegin"] =
522                 ListingsParam("", false, ALL, "", empty_hint);
523         all_params_["escepeend"] =
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 }
592
593
594 ListingsParam const & ParValidator::validate(string const & key,
595                 string const & par) const
596 {
597         ListingsParam const & lparam = param(key);
598         docstring s = lparam.validate(par);
599         if (!s.empty())
600                 throw invalidParam(bformat(_("Parameter %1$s: "), from_utf8(key)) + s);
601         return lparam;
602 }
603
604
605 ListingsParam const & ParValidator::param(string const & name) const
606 {
607         if (name.empty())
608                 throw invalidParam(_("Invalid (empty) listing parameter name."));
609
610         if (name[0] == '?') {
611                 string suffix = trim(string(name, 1));
612                 string param_names;
613                 ListingsParams::const_iterator it = all_params_.begin();
614                 ListingsParams::const_iterator end = all_params_.end();
615                 for (; it != end; ++it) {
616                         if (suffix.empty() || contains(it->first, suffix)) {
617                                 if (!param_names.empty())
618                                         param_names += ", ";
619                                 param_names += it->first;
620                         }
621                 }
622                 if (suffix.empty())
623                         throw invalidParam(bformat(
624                                         _("Available listing parameters are %1$s"), from_ascii(param_names)));
625                 else
626                         throw invalidParam(bformat(
627                                         _("Available listings parameters containing string \"%1$s\" are %2$s"), 
628                                                 from_utf8(suffix), from_utf8(param_names)));
629         }
630  
631         // do not validate keys starting with @
632         if (name[0] == '@')
633                 return all_params_.find("@")->second;
634
635         // locate name in parameter table
636         ListingsParams::const_iterator it = all_params_.find(name);
637         if (it != all_params_.end())
638                 return it->second;
639
640         // otherwise, produce a meaningful error message.
641         string matching_names;
642         ListingsParams::const_iterator end = all_params_.end();
643         for (it = all_params_.begin(); it != end; ++it) {
644                 if (prefixIs(it->first, name)) {
645                         if (!matching_names.empty())
646                                 matching_names += ", ";
647                         matching_names += it->first;
648                 }
649         }
650         if (matching_names.empty())
651                 throw invalidParam(bformat(_("Unknown listing parameter name: %1$s. "
652                         "Prefix this parameter with @ to bypass validation."),
653                                                     from_utf8(name)));
654         else
655                 throw invalidParam(bformat(_("Parameters starting with '%1$s': %2$s"),
656                                                     from_utf8(name), from_utf8(matching_names)));
657 }
658
659 } // namespace anon.
660
661 InsetListingsParams::InsetListingsParams()
662         : inline_(false), params_(), status_(InsetCollapsable::Open)
663 {
664 }
665
666
667 InsetListingsParams::InsetListingsParams(string const & par, bool in,
668                 InsetCollapsable::CollapseStatus s)
669         : inline_(in), params_(), status_(s)
670 {
671         // this will activate parameter validation.
672         fromEncodedString(par);
673 }
674
675
676 void InsetListingsParams::write(ostream & os) const
677 {
678         if (inline_)
679                 os << "true ";
680         else
681                 os << "false ";
682         os << status_ << " \""  << encodedString() << "\"";
683 }
684
685
686 void InsetListingsParams::read(Lexer & lex)
687 {
688         lex >> inline_;
689         int s;
690         lex >> s;
691         if (lex)
692                 status_ = static_cast<InsetCollapsable::CollapseStatus>(s);
693         string par;
694         lex >> par;
695         fromEncodedString(par);
696 }
697
698
699 string InsetListingsParams::params(string const & sep, bool valid_key) const
700 {
701         string par;
702         for (map<string, string>::const_iterator it = params_.begin();
703                 it != params_.end(); ++it) {
704                 if (!par.empty())
705                         par += sep;
706                 // key=value,key=value1 is stored in params_ as key=value,key_=value1. 
707                 string key = rtrim(it->first, "_");
708                 // remove prefix @ which is used by a parameter to bypass validation
709                 if (valid_key)
710                         key = ltrim(key, "@");
711                 if (it->second.empty())
712                         par += key;
713                 else
714                         par += key + '=' + it->second;
715         }
716         return par;
717 }
718
719
720 void InsetListingsParams::addParam(string const & key, string const & value)
721 {
722         if (key.empty())
723                 return;
724
725         static ParValidator par_validator;
726
727         // exception may be thown.
728         ListingsParam const & lparam = par_validator.validate(key, value);
729         // duplicate parameters!
730         string keyname = key;
731         if (params_.find(key) != params_.end())
732                 // key=value,key=value1 is allowed in listings
733                 // use key_, key__, key___ etc to avoid name conflict
734                 while (params_.find(keyname += '_') != params_.end());
735         // check onoff flag
736         // onoff parameter with value false
737         if (lparam.onoff_ && (value == "false" || value == "{false}"))
738                 params_[keyname] = string();
739         // if the parameter is surrounded with {}, good
740         else if (prefixIs(value, "{") && suffixIs(value, "}"))
741                 params_[keyname] = value;
742         // otherwise, check if {} is needed. Add {} to all values with
743         // non-ascii/number characters, just to be safe
744         else {
745                 bool has_special_char = false;
746                 for (size_t i = 0; i < value.size(); ++i)
747                         if (!isAlphaASCII(value[i]) && !isDigit(value[i])) {
748                                 has_special_char = true;
749                                 break;
750                         }
751                 if (has_special_char)
752                         params_[keyname] = "{" + value + "}";
753                 else
754                         params_[keyname] = value;
755         }
756 }
757
758
759 void InsetListingsParams::addParams(string const & par)
760 {
761         string key;
762         string value;
763         bool isValue = false;
764         int braces = 0;
765         for (size_t i = 0; i < par.size(); ++i) {
766                 // end of par
767                 if (par[i] == '\n') {
768                         addParam(trim(key), trim(value));
769                         key = string();
770                         value = string();
771                         isValue = false;
772                         continue;
773                 } else if (par[i] == ',' && braces == 0) {
774                         addParam(trim(key), trim(value));
775                         key = string();
776                         value = string();
777                         isValue = false;
778                         continue;
779                 } else if (par[i] == '=' && braces == 0) {
780                         isValue = true;
781                         continue;
782                 } else if (par[i] == '{' && par[i - 1] == '=')
783                         braces ++;
784                 else if (par[i] == '}'
785                         && (i == par.size() - 1 || par[i + 1] == ',' || par[i + 1] == '\n'))
786                         braces --;
787
788                 if (isValue)
789                         value += par[i];
790                 else
791                         key += par[i];
792         }
793         if (!trim(key).empty())
794                 addParam(trim(key), trim(value));
795 }
796
797
798 void InsetListingsParams::setParams(string const & par)
799 {
800         params_.clear();
801         addParams(par);
802 }
803
804
805 string InsetListingsParams::encodedString() const
806 {
807         // Encode string!
808         // '"' is handled differently because it will
809         // terminate a lyx token.
810         string par = params();
811         // '"' is now &quot;  ==> '"' is now &amp;quot;
812         par = subst(par, "&", "&amp;");
813         // '"' is now &amp;quot; ==> '&quot;' is now &amp;quot;
814         par = subst(par, "\"", "&quot;");
815         return par;
816 }
817
818
819 string InsetListingsParams::separatedParams(bool keepComma) const
820 {
821         if (keepComma)
822                 return params(",\n");
823         else
824                 return params("\n");
825 }
826
827
828 void InsetListingsParams::fromEncodedString(string const & in)
829 {
830         // Decode string! Reversal of encodedString
831         string par = in;
832         // '&quot;' is now &amp;quot; ==> '"' is now &amp;quot;
833         par = subst(par, "&quot;", "\"");
834         //  '"' is now &amp;quot; ==> '"' is now &quot;
835         par = subst(par, "&amp;", "&");
836         setParams(par);
837 }
838
839
840 bool InsetListingsParams::isFloat() const
841 {
842         return params_.find("float") != params_.end();
843 }
844
845
846 string InsetListingsParams::getParamValue(string const & param) const
847 {
848         // is this parameter defined?
849         map<string, string>::const_iterator it = params_.find(param);
850         string par = (it == params_.end()) ? string() : it->second;
851         if (prefixIs(par, "{") && suffixIs(par, "}"))
852                 return par.substr(1, par.size() - 2);
853         else
854                 return par;
855 }
856
857
858 } // namespace lyx