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