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