]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Change cursor shape for clickable math insets
[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                 // Add new line between paragraphs in displayed listings.
316                 // Exception: merged paragraphs in change tracking mode.
317                 // Also, for the inline case, if there are multiple paragraphs
318                 // they are simply joined. Otherwise, expect latex errors.
319                 if (par != end && !isInline && !captionline && !par->parEndChange().deleted())
320                         code += "\n";
321         }
322         if (isInline) {
323                 static const docstring delimiters =
324                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
325
326                 size_t pos = delimiters.find_first_not_of(code);
327
328                 // This code piece contains all possible special character? !!!
329                 // Replace ! with a warning message and use ! as delimiter.
330                 if (pos == string::npos) {
331                         docstring delim_error = "<" + _("LyX Warning: ")
332                                 + _("no more lstline delimiters available") + ">";
333                         code = subst(code, from_ascii("!"), delim_error);
334                         pos = 0;
335                         if (!runparams.dryrun && !runparams.silent) {
336                                 // FIXME: warning should be passed to the error dialog
337                                 frontend::Alert::warning(_("Running out of delimiters"),
338                                 _("For inline program listings, one character must be reserved\n"
339                                   "as a delimiter. One of the listings, however, uses all available\n"
340                                   "characters, so none is left for delimiting purposes.\n"
341                                   "For the time being, I have replaced '!' by a warning, but you\n"
342                                   "must investigate!"));
343                         }
344                 }
345                 docstring const delim(1, delimiters[pos]);
346                 if (use_minted) {
347                         os << "\\mintinline";
348                         if (!param_string.empty())
349                                 os << "[" << from_utf8(param_string) << "]";
350                         os << "{" << ascii_lowercase(minted_language) << "}";
351                 } else {
352                         os << "\\lstinline";
353                         if (!param_string.empty())
354                                 os << "[" << from_utf8(param_string) << "]";
355                         else if (pos >= delimiters.find('Q'))
356                                 // We need to terminate the command before
357                                 // the delimiter
358                                 os << " ";
359                 }
360                 os << delim << code << delim;
361         } else if (use_minted) {
362                 OutputParams rp = runparams;
363                 rp.moving_arg = true;
364                 TexString caption = getCaption(rp);
365                 if (isfloat) {
366                         os << breakln << "\\begin{listing}";
367                         if (!float_placement.empty())
368                                 os << '[' << float_placement << "]";
369                 } else if (captionfirst && !caption.str.empty()) {
370                         os << breakln << "\\lyxmintcaption[t]{"
371                            << move(caption) << "}\n";
372                 }
373                 os << breakln << "\\begin{minted}";
374                 if (!param_string.empty())
375                         os << "[" << param_string << "]";
376                 os << "{" << ascii_lowercase(minted_language) << "}\n"
377                    << code << breakln << "\\end{minted}\n";
378                 if (isfloat) {
379                         if (!caption.str.empty())
380                                 os << "\\caption{" << move(caption) << "}\n";
381                         os << "\\end{listing}\n";
382                 } else if (!captionfirst && !caption.str.empty()) {
383                         os << breakln << "\\lyxmintcaption[b]{"
384                            << move(caption) << "}";
385                 }
386         } else {
387                 OutputParams rp = runparams;
388                 rp.moving_arg = true;
389                 TexString caption = getCaption(rp);
390                 os << breakln << "\\begin{lstlisting}";
391                 if (param_string.empty() && caption.str.empty())
392                         os << "\n";
393                 else {
394                         if (!runparams.nice)
395                                 os << safebreakln;
396                         os << "[";
397                         if (!caption.str.empty()) {
398                                 os << "caption={" << move(caption) << '}';
399                                 if (!param_string.empty())
400                                         os << ',';
401                         }
402                         os << from_utf8(param_string) << "]\n";
403                 }
404                 os << code << breakln << "\\end{lstlisting}\n";
405         }
406
407         if (encoding_switched){
408                 // Switch back
409                 switchEncoding(os.os(), buffer().params(),
410                                runparams, *save_enc, true, true);
411                 os << "\\egroup" << breakln;
412                 runparams.encoding = save_enc;
413         }
414
415         if (!uncodable.empty() && !runparams.silent) {
416                 // issue a warning about omitted characters
417                 // FIXME: should be passed to the error dialog
418                 if (fixedlstenc)
419                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
420                                 bformat(_("The following characters in one of the program listings are\n"
421                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
422                                           "This is due to a restriction of the listings package, which does\n"
423                                           "not support your encoding '%2$s'.\n"
424                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
425                                           "might help."),
426                                 uncodable, _(runparams.encoding->guiName())));
427                 else
428                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
429                                 bformat(_("The following characters in one of the program listings are\n"
430                                           "not representable in the current encoding and have been omitted:\n%1$s."),
431                                 uncodable));
432         }
433 }
434
435
436 docstring InsetListings::xhtml(XMLStream & os, OutputParams const & rp) const
437 {
438         odocstringstream ods;
439         XMLStream out(ods);
440
441         bool const isInline = params().isInline();
442         if (isInline)
443                 out << xml::CompTag("br");
444         else {
445                 out << xml::StartTag("div", "class='float-listings'");
446                 docstring caption = getCaptionHTML(rp);
447                 if (!caption.empty())
448                         out << xml::StartTag("div", "class='listings-caption'")
449                             << XMLStream::ESCAPE_NONE
450                             << caption << xml::EndTag("div");
451         }
452
453         InsetLayout const & il = getLayout();
454         string const & tag = il.htmltag();
455         string attr = "class ='listings";
456         string const lang = params().getParamValue("language");
457         if (!lang.empty())
458                 attr += " " + lang;
459         attr += "'";
460         out << xml::StartTag(tag, attr);
461         OutputParams newrp = rp;
462         newrp.html_disable_captions = true;
463         // We don't want to convert dashes here. That's the only conversion we
464         // do for XHTML, so this is safe.
465         newrp.pass_thru = true;
466         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
467         out << xml::EndTag(tag);
468
469         if (isInline) {
470                 out << xml::CompTag("br");
471                 // escaping will already have been done
472                 os << XMLStream::ESCAPE_NONE << ods.str();
473         } else {
474                 out << xml::EndTag("div");
475                 // In this case, this needs to be deferred, but we'll put it
476                 // before anything the text itself deferred.
477                 def = ods.str() + '\n' + def;
478         }
479         return def;
480 }
481
482
483 void InsetListings::docbook(XMLStream & xs, OutputParams const & rp) const
484 {
485         InsetLayout const & il = getLayout();
486         bool isInline = params().isInline();
487
488         if (!isInline && !xs.isLastTagCR())
489                 xs << xml::CR();
490
491         // In case of caption, the code must be wrapped, for instance in a figure. Also detect if there is a label.
492         // http://www.sagehill.net/docbookxsl/ProgramListings.html
493         // TODO: parts of this code could be merged with InsetFloat and findLabelInParagraph.
494         InsetCaption const * caption = getCaptionInset();
495         if (caption) {
496                 InsetLabel const * label = getLabelInset();
497
498                 // Ensure that the label will not be output a second time as an anchor.
499                 OutputParams rpNoLabel = rp;
500                 if (label)
501                         rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
502
503                 // Prepare the right set of attributes, including the label.
504                 docstring attr = from_ascii("type='listing'");
505                 if (label)
506                         attr += " xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
507
508                 // Finally, generate the wrapper (including the label).
509                 xs << xml::StartTag("figure", attr);
510                 xs << xml::CR();
511                 xs << xml::StartTag("title");
512                 xs << XMLStream::ESCAPE_NONE << getCaptionDocBook(rpNoLabel);
513                 xs << xml::EndTag("title");
514                 xs << xml::CR();
515         }
516
517         // Forge the attributes.
518         std::string attrs;
519         if (!il.docbookattr().empty())
520                 attrs += " role=\"" + il.docbookattr() + "\"";
521         std::string const lang = params().getParamValue("language");
522         if (!lang.empty())
523                 attrs += " language=\"" + lang + "\"";
524
525         // Determine the tag to use. Use the layout-defined value if outside a paragraph.
526         std::string tag = il.docbooktag();
527         if (isInline)
528                 tag = "code";
529
530         // Start the listing.
531         xs << xml::StartTag(tag, attrs);
532         xs.startDivision(false);
533
534         // Deal with the content of the listing.
535         OutputParams newrp = rp;
536         newrp.pass_thru = true;
537         newrp.docbook_make_pars = false;
538         newrp.par_begin = 0;
539         newrp.par_end = text().paragraphs().size();
540         newrp.docbook_in_listing = true;
541
542         docbookParagraphs(text(), buffer(), xs, newrp);
543
544         // Done with the listing.
545         xs.endDivision();
546         xs << xml::EndTag(tag);
547         if (!isInline)
548                 xs << xml::CR();
549
550         if (caption) {
551                 xs << xml::EndTag("figure");
552                 xs << xml::CR();
553         }
554 }
555
556
557 string InsetListings::contextMenuName() const
558 {
559         return "context-listings";
560 }
561
562
563 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
564 {
565         switch (cmd.action()) {
566
567         case LFUN_INSET_MODIFY: {
568                 cur.recordUndoInset(this);
569                 InsetListings::string2params(to_utf8(cmd.argument()), params());
570                 break;
571         }
572
573         case LFUN_INSET_DIALOG_UPDATE:
574                 cur.bv().updateDialog("listings", params2string(params()));
575                 break;
576
577         default:
578                 InsetCaptionable::doDispatch(cur, cmd);
579                 break;
580         }
581 }
582
583
584 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
585         FuncStatus & status) const
586 {
587         switch (cmd.action()) {
588                 case LFUN_INSET_MODIFY:
589                 case LFUN_INSET_DIALOG_UPDATE:
590                         status.setEnabled(true);
591                         return true;
592                 case LFUN_CAPTION_INSERT: {
593                         // the inset outputs at most one caption
594                         if (params().isInline() || getCaptionInset()) {
595                                 status.setEnabled(false);
596                                 return true;
597                         }
598                 }
599                 // fall through
600                 default:
601                         return InsetCaptionable::getStatus(cur, cmd, status);
602         }
603 }
604
605
606 docstring const InsetListings::buttonLabel(BufferView const & bv) const
607 {
608         // FIXME UNICODE
609         docstring const locked = tempfile_ ? docstring(1, 0x1F512) : docstring();
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