]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
DocBook: refactor code about retrieving captions and labels.
[lyx.git] / src / insets / InsetListings.cpp
1 /**
2  * \file InsetListings.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  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetListings.h"
15
16 #include "Buffer.h"
17 #include "BufferView.h"
18 #include "BufferParams.h"
19 #include "Counters.h"
20 #include "Cursor.h"
21 #include "DispatchResult.h"
22 #include "Encoding.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetCaption.h"
26 #include "InsetLabel.h"
27 #include "Language.h"
28 #include "LaTeXFeatures.h"
29 #include "Lexer.h"
30 #include "output_latex.h"
31 #include "output_docbook.h"
32 #include "output_xhtml.h"
33 #include "OutputParams.h"
34 #include "TextClass.h"
35 #include "TexRow.h"
36 #include "texstream.h"
37
38 #include "support/debug.h"
39 #include "support/docstream.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/lassert.h"
43
44 #include "frontends/alert.h"
45 #include "frontends/Application.h"
46
47 #include "support/regex.h"
48
49 #include <sstream>
50
51 using namespace std;
52 using namespace lyx::support;
53
54 namespace lyx {
55
56
57 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
58         : InsetCaptionable(buf,"listing")
59 {
60         params_.setMinted(buffer().params().use_minted);
61         status_ = par.status();
62 }
63
64
65 InsetListings::~InsetListings()
66 {
67         hideDialogs("listings", this);
68 }
69
70
71 Inset::RowFlags InsetListings::rowFlags() const
72 {
73         return params().isInline() || params().isFloat() ? Inline : Display | AlignLeft;
74 }
75
76
77 docstring InsetListings::layoutName() const
78 {
79         if (buffer().params().use_minted)
80                 return from_ascii("MintedListings");
81         else
82                 return from_ascii("Listings");
83 }
84
85
86 void InsetListings::write(ostream & os) const
87 {
88         os << "listings" << "\n";
89         InsetListingsParams const & par = params();
90         // parameter string is encoded to be a valid lyx token.
91         string opt = par.encodedString();
92         if (!opt.empty())
93                 os << "lstparams \"" << opt << "\"\n";
94         if (par.isInline())
95                 os << "inline true\n";
96         else
97                 os << "inline false\n";
98         InsetCaptionable::write(os);
99 }
100
101
102 void InsetListings::read(Lexer & lex)
103 {
104         while (lex.isOK()) {
105                 lex.next();
106                 string token = lex.getString();
107                 if (token == "lstparams") {
108                         lex.next();
109                         string const value = lex.getString();
110                         params().fromEncodedString(value);
111                 } else if (token == "inline") {
112                         lex.next();
113                         params().setInline(lex.getBool());
114                 } else {
115                         // no special option, push back 'status' etc
116                         lex.pushToken(token);
117                         break;
118                 }
119         }
120         InsetCaptionable::read(lex);
121 }
122
123
124 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
125                                                Encoding const * outer_enc) const
126 {
127         // The listings package cannot deal with multi-byte-encoded
128         // glyphs, except for Xe/LuaTeX (with non-TeX fonts) or pLaTeX.
129         // Minted can deal with all encodings.
130         if (buffer().params().use_minted
131                 || inner_enc->name() == "utf8-plain"
132                 || inner_enc->package() == Encoding::japanese
133                 || inner_enc->hasFixedWidth())
134                 return 0;
135
136         // We try if there's a singlebyte encoding for the outer
137         // language; if not, fall back to latin1.
138         // Power-users can set inputenc to utf8-plain to bypass this workaround
139         // and provide alternatives in the user-preamble.
140         return (outer_enc->hasFixedWidth()) ?
141                         outer_enc : encodings.fromLyXName("iso8859-1");
142 }
143
144
145 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
146 {
147         string param_string = params().params();
148         // NOTE: I use {} to quote text, which is an experimental feature
149         // of the listings package (see page 25 of the manual)
150         bool const isInline = params().isInline();
151         bool const use_minted = buffer().params().use_minted;
152         static regex const reg1("(.*)(basicstyle=\\{)([^\\}]*)(\\\\ttfamily)([^\\}]*)(\\})(.*)");
153         static regex const reg2("(.*)(basicstyle=\\{)([^\\}]*)(\\\\rmfamily)([^\\}]*)(\\})(.*)");
154         static regex const reg3("(.*)(basicstyle=\\{)([^\\}]*)(\\\\sffamily)([^\\}]*)(\\})(.*)");
155         static regex const reg4("(.*)(basicstyle=\\{)([^\\}]*)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))([^\\}]*)(\\})(.*)");
156         static regex const reg5("(.*)(fontfamily=)(tt|sf|rm)(.*)");
157         static regex const reg6("(.*)(fontsize=\\{)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))(\\})(.*)");
158         if (use_minted) {
159                 // If params have been entered with "listings", and then the user switched to "minted",
160                 // we have params that need to be translated.
161                 // FIXME: We should use a backend-abstract syntax in listings params instead!
162                 // Substitute fontstyle option
163                 smatch sub;
164                 if (regex_match(param_string, sub, reg1))
165                         param_string = sub.str(1) + "fontfamily=tt," + sub.str(2) + sub.str(3)
166                                         + sub.str(5) + sub.str(6) + sub.str(7);
167                 if (regex_match(param_string, sub, reg2))
168                         param_string = sub.str(1) + "fontfamily=rm," + sub.str(2) + sub.str(3)
169                                         + sub.str(5) + sub.str(6) + sub.str(7);
170                 if (regex_match(param_string, sub, reg3))
171                         param_string = sub.str(1) + "fontfamily=sf," + sub.str(2) + sub.str(3)
172                                         + sub.str(5) + sub.str(6) + sub.str(7);
173                 // as well as fontsize option
174                 if (regex_match(param_string, sub, reg4))
175                         param_string = sub.str(1) + "fontsize={" + sub.str(4) + sub.str(3) + sub.str(7) + sub.str(8);
176         } else {
177                 // And the same vice versa
178                 // Substitute fontstyle option
179                 smatch sub;
180                 string basicstyle;
181                 if (regex_match(param_string, sub, reg5)) {
182                         basicstyle = "\\" + sub.str(3) + "family";
183                         param_string = sub.str(1) + sub.str(4);
184                 }
185                 // as well as fontsize option
186                 if (regex_match(param_string, sub, reg6)) {
187                         basicstyle += sub.str(3);
188                         param_string = sub.str(1) + sub.str(6);
189                 }
190                 if (!basicstyle.empty())
191                         param_string = rtrim(param_string, ",") + ",basicstyle={" + basicstyle + "}";
192         }
193         if (runparams.use_polyglossia && runparams.local_font->isRightToLeft()) {
194                 // We need to use the *latin switches (#11554)
195                 smatch sub;
196                 if (regex_match(param_string, sub, reg1))
197                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
198                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
199                 if (regex_match(param_string, sub, reg2))
200                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
201                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
202                 if (regex_match(param_string, sub, reg3))
203                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
204                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
205         }
206         string minted_language;
207         string float_placement;
208         bool const isfloat = params().isFloat();
209         if (use_minted && (isfloat || contains(param_string, "language="))) {
210                 // Get float placement and/or language of the code,
211                 // then remove the relative options.
212                 vector<string> opts =
213                         getVectorFromString(param_string, ",", false);
214                 for (size_t i = 0; i < opts.size(); ++i) {
215                         if (prefixIs(opts[i], "float")) {
216                                 if (prefixIs(opts[i], "float="))
217                                         float_placement = opts[i].substr(6);
218                                 opts.erase(opts.begin() + int(i--));
219                         }
220                         else if (prefixIs(opts[i], "language=")) {
221                                 minted_language = opts[i].substr(9);
222                                 opts.erase(opts.begin() + int(i--));
223                         }
224                 }
225                 param_string = getStringFromVector(opts, ",");
226         }
227         // Minted needs a language specification
228         if (minted_language.empty()) {
229                 // If a language has been set globally, use that,
230                 // otherwise use TeX by default
231                 string const & blp = buffer().params().listings_params;
232                 size_t start = blp.find("language=");
233                 if (start != string::npos) {
234                         start += strlen("language=");
235                         size_t len = blp.find(",", start);
236                         if (len != string::npos)
237                                 len -= start;
238                         minted_language = blp.substr(start, len);
239                 } else
240                         minted_language = "TeX";
241         }
242
243         // get the paragraphs. We can not output them directly to given odocstream
244         // because we can not yet determine the delimiter character of \lstinline
245         docstring code;
246         docstring uncodable;
247         ParagraphList::const_iterator par = paragraphs().begin();
248         ParagraphList::const_iterator end = paragraphs().end();
249
250         bool encoding_switched = false;
251         Encoding const * const save_enc = runparams.encoding;
252
253         Encoding const * const outer_encoding =
254                 (runparams.local_font != 0) ?
255                         runparams.local_font->language()->encoding()
256                         : buffer().params().language->encoding();
257         Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
258         if (fixedlstenc) {
259                 // We need to switch to a singlebyte encoding, due to
260                 // the restrictions of the listings package (see above).
261                 // This needs to be consistent with
262                 // LaTeXFeatures::getTClassI18nPreamble().
263                 // We need to put this into a group in order to prevent encoding leaks
264                 // (happens with cprotect).
265                 os << "\\bgroup";
266                 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
267                 runparams.encoding = fixedlstenc;
268                 encoding_switched = true;
269         }
270
271         bool const captionfirst = !isfloat && par->isInset(0)
272                                 && par->getInset(0)->lyxCode() == CAPTION_CODE;
273
274         while (par != end) {
275                 pos_type const siz = par->size();
276                 bool captionline = false;
277                 for (pos_type i = 0; i < siz; ++i) {
278                         if (i == 0 && par->isInset(i) && i + 1 == siz)
279                                 captionline = true;
280                         // ignore all struck out text and (caption) insets
281                         if (par->isDeleted(i)
282                             || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
283                                 continue;
284                         if (par->isInset(i)) {
285                                 // Currently, this can only be a quote inset
286                                 // that is output as plain quote here, but
287                                 // we use more generic code anyway.
288                                 otexstringstream ots;
289                                 OutputParams rp = runparams;
290                                 rp.pass_thru = true;
291                                 par->getInset(i)->latex(ots, rp);
292                                 code += ots.str();
293                                 continue;
294                         }
295                         char_type c = par->getChar(i);
296                         // we can only output characters covered by the current
297                         // encoding!
298                         try {
299                                 if (runparams.encoding->encodable(c))
300                                         code += c;
301                                 else if (runparams.dryrun) {
302                                         code += "<" + _("LyX Warning: ")
303                                            + _("uncodable character") + " '";
304                                         code += docstring(1, c);
305                                         code += "'>";
306                                 } else
307                                         uncodable += c;
308                         } catch (EncodingException & /* e */) {
309                                 if (runparams.dryrun) {
310                                         code += "<" + _("LyX Warning: ")
311                                            + _("uncodable character") + " '";
312                                         code += docstring(1, c);
313                                         code += "'>";
314                                 } else
315                                         uncodable += c;
316                         }
317                 }
318                 ++par;
319                 // for the inline case, if there are multiple paragraphs
320                 // they are simply joined. Otherwise, expect latex errors.
321                 if (par != end && !isInline && !captionline)
322                         code += "\n";
323         }
324         if (isInline) {
325                 static const docstring delimiters =
326                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
327
328                 size_t pos = delimiters.find_first_not_of(code);
329
330                 // This code piece contains all possible special character? !!!
331                 // Replace ! with a warning message and use ! as delimiter.
332                 if (pos == string::npos) {
333                         docstring delim_error = "<" + _("LyX Warning: ")
334                                 + _("no more lstline delimiters available") + ">";
335                         code = subst(code, from_ascii("!"), delim_error);
336                         pos = 0;
337                         if (!runparams.dryrun && !runparams.silent) {
338                                 // FIXME: warning should be passed to the error dialog
339                                 frontend::Alert::warning(_("Running out of delimiters"),
340                                 _("For inline program listings, one character must be reserved\n"
341                                   "as a delimiter. One of the listings, however, uses all available\n"
342                                   "characters, so none is left for delimiting purposes.\n"
343                                   "For the time being, I have replaced '!' by a warning, but you\n"
344                                   "must investigate!"));
345                         }
346                 }
347                 docstring const delim(1, delimiters[pos]);
348                 if (use_minted) {
349                         os << "\\mintinline";
350                         if (!param_string.empty())
351                                 os << "[" << from_utf8(param_string) << "]";
352                         os << "{" << ascii_lowercase(minted_language) << "}";
353                 } else {
354                         os << "\\lstinline";
355                         if (!param_string.empty())
356                                 os << "[" << from_utf8(param_string) << "]";
357                         else if (pos >= delimiters.find('Q'))
358                                 // We need to terminate the command before
359                                 // the delimiter
360                                 os << " ";
361                 }
362                 os << delim << code << delim;
363         } else if (use_minted) {
364                 OutputParams rp = runparams;
365                 rp.moving_arg = true;
366                 TexString caption = getCaption(rp);
367                 if (isfloat) {
368                         os << breakln << "\\begin{listing}";
369                         if (!float_placement.empty())
370                                 os << '[' << float_placement << "]";
371                 } else if (captionfirst && !caption.str.empty()) {
372                         os << breakln << "\\lyxmintcaption[t]{"
373                            << move(caption) << "}\n";
374                 }
375                 os << breakln << "\\begin{minted}";
376                 if (!param_string.empty())
377                         os << "[" << param_string << "]";
378                 os << "{" << ascii_lowercase(minted_language) << "}\n"
379                    << code << breakln << "\\end{minted}\n";
380                 if (isfloat) {
381                         if (!caption.str.empty())
382                                 os << "\\caption{" << move(caption) << "}\n";
383                         os << "\\end{listing}\n";
384                 } else if (!captionfirst && !caption.str.empty()) {
385                         os << breakln << "\\lyxmintcaption[b]{"
386                            << move(caption) << "}";
387                 }
388         } else {
389                 OutputParams rp = runparams;
390                 rp.moving_arg = true;
391                 TexString caption = getCaption(rp);
392                 os << breakln << "\\begin{lstlisting}";
393                 if (param_string.empty() && caption.str.empty())
394                         os << "\n";
395                 else {
396                         if (!runparams.nice)
397                                 os << safebreakln;
398                         os << "[";
399                         if (!caption.str.empty()) {
400                                 os << "caption={" << move(caption) << '}';
401                                 if (!param_string.empty())
402                                         os << ',';
403                         }
404                         os << from_utf8(param_string) << "]\n";
405                 }
406                 os << code << breakln << "\\end{lstlisting}\n";
407         }
408
409         if (encoding_switched){
410                 // Switch back
411                 switchEncoding(os.os(), buffer().params(),
412                                runparams, *save_enc, true, true);
413                 os << "\\egroup" << breakln;
414                 runparams.encoding = save_enc;
415         }
416
417         if (!uncodable.empty() && !runparams.silent) {
418                 // issue a warning about omitted characters
419                 // FIXME: should be passed to the error dialog
420                 if (fixedlstenc)
421                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
422                                 bformat(_("The following characters in one of the program listings are\n"
423                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
424                                           "This is due to a restriction of the listings package, which does\n"
425                                           "not support your encoding '%2$s'.\n"
426                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
427                                           "might help."),
428                                 uncodable, _(runparams.encoding->guiName())));
429                 else
430                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
431                                 bformat(_("The following characters in one of the program listings are\n"
432                                           "not representable in the current encoding and have been omitted:\n%1$s."),
433                                 uncodable));
434         }
435 }
436
437
438 docstring InsetListings::xhtml(XMLStream & os, OutputParams const & rp) const
439 {
440         odocstringstream ods;
441         XMLStream out(ods);
442
443         bool const isInline = params().isInline();
444         if (isInline)
445                 out << xml::CompTag("br");
446         else {
447                 out << xml::StartTag("div", "class='float-listings'");
448                 docstring caption = getCaptionHTML(rp);
449                 if (!caption.empty())
450                         out << xml::StartTag("div", "class='listings-caption'")
451                             << XMLStream::ESCAPE_NONE
452                             << caption << xml::EndTag("div");
453         }
454
455         InsetLayout const & il = getLayout();
456         string const & tag = il.htmltag();
457         string attr = "class ='listings";
458         string const lang = params().getParamValue("language");
459         if (!lang.empty())
460                 attr += " " + lang;
461         attr += "'";
462         out << xml::StartTag(tag, attr);
463         OutputParams newrp = rp;
464         newrp.html_disable_captions = true;
465         // We don't want to convert dashes here. That's the only conversion we
466         // do for XHTML, so this is safe.
467         newrp.pass_thru = true;
468         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
469         out << xml::EndTag(tag);
470
471         if (isInline) {
472                 out << xml::CompTag("br");
473                 // escaping will already have been done
474                 os << XMLStream::ESCAPE_NONE << ods.str();
475         } else {
476                 out << xml::EndTag("div");
477                 // In this case, this needs to be deferred, but we'll put it
478                 // before anything the text itself deferred.
479                 def = ods.str() + '\n' + def;
480         }
481         return def;
482 }
483
484
485 void InsetListings::docbook(XMLStream & xs, OutputParams const & rp) const
486 {
487         InsetLayout const & il = getLayout();
488         bool isInline = params().isInline();
489
490         if (!isInline && !xs.isLastTagCR())
491                 xs << xml::CR();
492
493         // In case of caption, the code must be wrapped, for instance in a figure. Also detect if there is a label.
494         // http://www.sagehill.net/docbookxsl/ProgramListings.html
495         // TODO: parts of this code could be merged with InsetFloat and findLabelInParagraph.
496         InsetCaption const * caption = getCaptionInset();
497         if (caption) {
498                 InsetLabel const * label = getLabelInset();
499
500                 // Ensure that the label will not be output a second time as an anchor.
501                 OutputParams rpNoLabel = rp;
502                 if (label)
503                         rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
504
505                 // Prepare the right set of attributes, including the label.
506                 docstring attr = from_ascii("type='listing'");
507                 if (label)
508                         attr += " xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
509
510                 // Finally, generate the wrapper (including the label).
511                 xs << xml::StartTag("figure", attr);
512                 xs << xml::CR();
513                 xs << xml::StartTag("title");
514                 xs << XMLStream::ESCAPE_NONE << getCaptionDocBook(rpNoLabel);
515                 xs << xml::EndTag("title");
516                 xs << xml::CR();
517         }
518
519         // Forge the attributes.
520         std::string attrs;
521         if (!il.docbookattr().empty())
522                 attrs += " role=\"" + il.docbookattr() + "\"";
523         std::string const lang = params().getParamValue("language");
524         if (!lang.empty())
525                 attrs += " language=\"" + lang + "\"";
526
527         // Determine the tag to use. Use the layout-defined value if outside a paragraph.
528         std::string tag = il.docbooktag();
529         if (isInline)
530                 tag = "code";
531
532         // Start the listing.
533         xs << xml::StartTag(tag, attrs);
534         xs.startDivision(false);
535
536         // Deal with the content of the listing.
537         OutputParams newrp = rp;
538         newrp.pass_thru = true;
539         newrp.docbook_make_pars = false;
540         newrp.par_begin = 0;
541         newrp.par_end = text().paragraphs().size();
542         newrp.docbook_in_listing = true;
543
544         docbookParagraphs(text(), buffer(), xs, newrp);
545
546         // Done with the listing.
547         xs.endDivision();
548         xs << xml::EndTag(tag);
549         if (!isInline)
550                 xs << xml::CR();
551
552         if (caption) {
553                 xs << xml::EndTag("figure");
554                 xs << xml::CR();
555         }
556 }
557
558
559 string InsetListings::contextMenuName() const
560 {
561         return "context-listings";
562 }
563
564
565 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
566 {
567         switch (cmd.action()) {
568
569         case LFUN_INSET_MODIFY: {
570                 cur.recordUndoInset(this);
571                 InsetListings::string2params(to_utf8(cmd.argument()), params());
572                 break;
573         }
574
575         case LFUN_INSET_DIALOG_UPDATE:
576                 cur.bv().updateDialog("listings", params2string(params()));
577                 break;
578
579         default:
580                 InsetCaptionable::doDispatch(cur, cmd);
581                 break;
582         }
583 }
584
585
586 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
587         FuncStatus & status) const
588 {
589         switch (cmd.action()) {
590                 case LFUN_INSET_MODIFY:
591                 case LFUN_INSET_DIALOG_UPDATE:
592                         status.setEnabled(true);
593                         return true;
594                 case LFUN_CAPTION_INSERT: {
595                         // the inset outputs at most one caption
596                         if (params().isInline() || getCaptionInset()) {
597                                 status.setEnabled(false);
598                                 return true;
599                         }
600                 }
601                 // fall through
602                 default:
603                         return InsetCaptionable::getStatus(cur, cmd, status);
604         }
605 }
606
607
608 docstring const InsetListings::buttonLabel(BufferView const & bv) const
609 {
610         // FIXME UNICODE
611         if (decoration() == InsetLayout::CLASSIC)
612                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
613         else
614                 return getNewLabel(_("Listing"));
615 }
616
617
618 void InsetListings::validate(LaTeXFeatures & features) const
619 {
620         features.useInsetLayout(getLayout());
621         string param_string = params().params();
622         if (buffer().params().use_minted) {
623                 features.require("minted");
624                 OutputParams rp = features.runparams();
625                 if (!params().isFloat() && !getCaption(rp).str.empty())
626                         features.require("lyxmintcaption");
627                 if (features.usePolyglossia() && features.hasRTLLanguage())
628                         // minted loads color, but color must be loaded before bidi
629                         // (i.e., polyglossia)
630                         features.require("color");
631         } else {
632                 features.require("listings");
633                 if (contains(param_string, "\\color"))
634                         features.require("color");
635         }
636         InsetCaptionable::validate(features);
637 }
638
639
640 bool InsetListings::showInsetDialog(BufferView * bv) const
641 {
642         bv->showDialog("listings", params2string(params()),
643                 const_cast<InsetListings *>(this));
644         return true;
645 }
646
647
648 TexString InsetListings::getCaption(OutputParams const & runparams) const
649 {
650         InsetCaption const * ins = getCaptionInset();
651         if (ins == 0)
652                 return TexString();
653
654         otexstringstream os;
655         ins->getArgs(os, runparams);
656         ins->getArgument(os, runparams);
657
658         // TODO: The code below should be moved to support, and then the test
659         //       in ../tests should be moved there as well.
660
661         // the caption may contain \label{} but the listings
662         // package prefer caption={}, label={}
663         TexString cap = os.release();
664         if (buffer().params().use_minted
665             || !contains(cap.str, from_ascii("\\label{")))
666                 return cap;
667         // convert from
668         //     blah1\label{blah2} blah3
669         // to
670         //     blah1 blah3},label={blah2
671         // to form options
672         //     caption={blah1 blah3},label={blah2}
673         //
674         // NOTE that } is not allowed in blah2.
675         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
676         string const new_cap("$1$3},label={$2");
677         // Remove potential \protect'ion of \label.
678         docstring capstr = subst(cap.str, from_ascii("\\protect\\label"),
679                                  from_ascii("\\label"));
680         // TexString validity: the substitution preserves the number of newlines.
681         // Moreover we assume that $2 does not contain newlines, so that the texrow
682         // information remains accurate.
683         // Replace '\n' with an improbable character from Private Use Area-A
684         // and then return to '\n' after the regex replacement.
685         capstr = subst(capstr, char_type('\n'), 0xffffd);
686         cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
687                         0xffffd, char_type('\n'));
688         return cap;
689 }
690
691
692 void InsetListings::string2params(string const & in,
693                                    InsetListingsParams & params)
694 {
695         params = InsetListingsParams();
696         if (in.empty())
697                 return;
698         istringstream data(in);
699         Lexer lex;
700         lex.setStream(data);
701         // discard "listings", which is only used to determine inset
702         lex.next();
703         params.read(lex);
704 }
705
706
707 string InsetListings::params2string(InsetListingsParams const & params)
708 {
709         ostringstream data;
710         data << "listings" << ' ';
711         params.write(data);
712         return data.str();
713 }
714
715
716 } // namespace lyx