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