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