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