2 * \file InsetListings.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
14 #include "InsetListings.h"
17 #include "BufferView.h"
18 #include "BufferParams.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "InsetCaption.h"
24 #include "InsetLabel.h"
25 #include "InsetLayout.h"
27 #include "LaTeXFeatures.h"
29 #include "output_latex.h"
30 #include "output_docbook.h"
31 #include "output_xhtml.h"
33 #include "texstream.h"
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"
41 #include "frontends/alert.h"
42 #include "frontends/Application.h"
48 using namespace lyx::support;
53 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
54 : InsetCaptionable(buf,"listing")
56 params_.setMinted(buffer().params().use_minted);
57 status_ = par.status();
61 InsetListings::~InsetListings()
63 hideDialogs("listings", this);
67 Inset::RowFlags InsetListings::rowFlags() const
69 return params().isInline() || params().isFloat() ? Inline : Display | AlignLeft;
73 docstring InsetListings::layoutName() const
75 if (buffer().params().use_minted)
76 return from_ascii("MintedListings");
78 return from_ascii("Listings");
82 void InsetListings::write(ostream & os) const
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();
89 os << "lstparams \"" << opt << "\"\n";
91 os << "inline true\n";
93 os << "inline false\n";
94 InsetCaptionable::write(os);
98 void InsetListings::read(Lexer & lex)
102 string token = lex.getString();
103 if (token == "lstparams") {
105 string const value = lex.getString();
106 params().fromEncodedString(value);
107 } else if (token == "inline") {
109 params().setInline(lex.getBool());
111 // no special option, push back 'status' etc
112 lex.pushToken(token);
116 InsetCaptionable::read(lex);
120 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
121 Encoding const * outer_enc) const
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())
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");
141 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
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))(\\})(.*)");
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
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);
173 // And the same vice versa
174 // Substitute fontstyle option
177 if (regex_match(param_string, sub, reg5)) {
178 basicstyle = "\\" + sub.str(3) + "family";
179 param_string = sub.str(1) + sub.str(4);
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);
186 if (!basicstyle.empty())
187 param_string = rtrim(param_string, ",") + ",basicstyle={" + basicstyle + "}";
189 if (runparams.use_polyglossia && runparams.local_font->isRightToLeft()) {
190 // We need to use the *latin switches (#11554)
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);
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--));
216 else if (prefixIs(opts[i], "language=")) {
217 minted_language = opts[i].substr(9);
218 opts.erase(opts.begin() + int(i--));
221 param_string = getStringFromVector(opts, ",");
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)
234 minted_language = blp.substr(start, len);
236 minted_language = "TeX";
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
243 ParagraphList::const_iterator par = paragraphs().begin();
244 ParagraphList::const_iterator end = paragraphs().end();
246 bool encoding_switched = false;
247 Encoding const * const save_enc = runparams.encoding;
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);
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).
262 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
263 runparams.encoding = fixedlstenc;
264 encoding_switched = true;
267 bool const captionfirst = !isfloat && par->isInset(0)
268 && par->getInset(0)->lyxCode() == CAPTION_CODE;
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)
276 // ignore all struck out text and (caption) insets
277 if (par->isDeleted(i)
278 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
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;
287 par->getInset(i)->latex(ots, rp);
291 char_type c = par->getChar(i);
292 // we can only output characters covered by the current
295 if (runparams.encoding->encodable(c))
297 else if (runparams.dryrun) {
298 code += "<" + _("LyX Warning: ")
299 + _("uncodable character") + " '";
300 code += docstring(1, c);
304 } catch (EncodingException & /* e */) {
305 if (runparams.dryrun) {
306 code += "<" + _("LyX Warning: ")
307 + _("uncodable character") + " '";
308 code += docstring(1, c);
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)
321 static const docstring delimiters =
322 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
324 size_t pos = delimiters.find_first_not_of(code);
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);
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!"));
343 docstring const delim(1, delimiters[pos]);
345 os << "\\mintinline";
346 if (!param_string.empty())
347 os << "[" << from_utf8(param_string) << "]";
348 os << "{" << ascii_lowercase(minted_language) << "}";
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
358 os << delim << code << delim;
359 } else if (use_minted) {
360 OutputParams rp = runparams;
361 rp.moving_arg = true;
362 TexString caption = getCaption(rp);
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";
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";
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) << "}";
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())
395 if (!caption.str.empty()) {
396 os << "caption={" << move(caption) << '}';
397 if (!param_string.empty())
400 os << from_utf8(param_string) << "]\n";
402 os << code << breakln << "\\end{lstlisting}\n";
405 if (encoding_switched){
407 switchEncoding(os.os(), buffer().params(),
408 runparams, *save_enc, true, true);
409 os << "\\egroup" << breakln;
410 runparams.encoding = save_enc;
413 if (!uncodable.empty() && !runparams.silent) {
414 // issue a warning about omitted characters
415 // FIXME: should be passed to the error dialog
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"
424 uncodable, _(runparams.encoding->guiName())));
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."),
434 docstring InsetListings::xhtml(XMLStream & os, OutputParams const & rp) const
436 odocstringstream ods;
439 bool const isInline = params().isInline();
441 out << xml::CompTag("br");
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");
451 InsetLayout const & il = getLayout();
452 string const & tag = il.htmltag();
453 string attr = "class ='listings";
454 string const lang = params().getParamValue("language");
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);
468 out << xml::CompTag("br");
469 // escaping will already have been done
470 os << XMLStream::ESCAPE_NONE << ods.str();
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;
481 void InsetListings::docbook(XMLStream & xs, OutputParams const & rp) const
483 InsetLayout const & il = getLayout();
484 bool isInline = params().isInline();
486 if (!isInline && !xs.isLastTagCR())
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();
494 InsetLabel const * label = getLabelInset();
496 // Ensure that the label will not be output a second time as an anchor.
497 OutputParams rpNoLabel = rp;
499 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
501 // Prepare the right set of attributes, including the label.
502 docstring attr = from_ascii("type='listing'");
504 attr += " xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
506 // Finally, generate the wrapper (including the label).
507 xs << xml::StartTag("figure", attr);
509 xs << xml::StartTag("title");
510 xs << XMLStream::ESCAPE_NONE << getCaptionDocBook(rpNoLabel);
511 xs << xml::EndTag("title");
515 // Forge the attributes.
517 if (!il.docbookattr().empty())
518 attrs += " role=\"" + il.docbookattr() + "\"";
519 std::string const lang = params().getParamValue("language");
521 attrs += " language=\"" + lang + "\"";
523 // Determine the tag to use. Use the layout-defined value if outside a paragraph.
524 std::string tag = il.docbooktag();
528 // Start the listing.
529 xs << xml::StartTag(tag, attrs);
530 xs.startDivision(false);
532 // Deal with the content of the listing.
533 OutputParams newrp = rp;
534 newrp.pass_thru = true;
535 newrp.docbook_make_pars = false;
537 newrp.par_end = text().paragraphs().size();
538 newrp.docbook_in_listing = true;
540 docbookParagraphs(text(), buffer(), xs, newrp);
542 // Done with the listing.
544 xs << xml::EndTag(tag);
549 xs << xml::EndTag("figure");
555 string InsetListings::contextMenuName() const
557 return "context-listings";
561 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
563 switch (cmd.action()) {
565 case LFUN_INSET_MODIFY: {
566 cur.recordUndoInset(this);
567 InsetListings::string2params(to_utf8(cmd.argument()), params());
571 case LFUN_INSET_DIALOG_UPDATE:
572 cur.bv().updateDialog("listings", params2string(params()));
576 InsetCaptionable::doDispatch(cur, cmd);
582 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
583 FuncStatus & status) const
585 switch (cmd.action()) {
586 case LFUN_INSET_MODIFY:
587 case LFUN_INSET_DIALOG_UPDATE:
588 status.setEnabled(true);
590 case LFUN_CAPTION_INSERT: {
591 // the inset outputs at most one caption
592 if (params().isInline() || getCaptionInset()) {
593 status.setEnabled(false);
599 return InsetCaptionable::getStatus(cur, cmd, status);
604 docstring const InsetListings::buttonLabel(BufferView const & bv) const
607 docstring const locked = tempfile_ ? docstring(1, 0x1F512) : docstring();
608 if (decoration() == InsetDecoration::CLASSIC)
609 return locked + (isOpen(bv) ? _("Listing") : getNewLabel(_("Listing")));
610 return locked + getNewLabel(_("Listing"));
614 void InsetListings::validate(LaTeXFeatures & features) const
616 features.useInsetLayout(getLayout());
617 string param_string = params().params();
618 if (buffer().params().use_minted) {
619 features.require("minted");
620 OutputParams rp = features.runparams();
621 if (!params().isFloat() && !getCaption(rp).str.empty())
622 features.require("lyxmintcaption");
623 if (features.usePolyglossia() && features.hasRTLLanguage())
624 // minted loads color, but color must be loaded before bidi
625 // (i.e., polyglossia)
626 features.require("color");
628 features.require("listings");
629 if (contains(param_string, "\\color"))
630 features.require("color");
632 InsetCaptionable::validate(features);
636 bool InsetListings::showInsetDialog(BufferView * bv) const
638 bv->showDialog("listings", params2string(params()),
639 const_cast<InsetListings *>(this));
644 TexString InsetListings::getCaption(OutputParams const & runparams) const
646 InsetCaption const * ins = getCaptionInset();
651 ins->getArgs(os, runparams);
652 ins->getArgument(os, runparams);
654 // TODO: The code below should be moved to support, and then the test
655 // in ../tests should be moved there as well.
657 // the caption may contain \label{} but the listings
658 // package prefer caption={}, label={}
659 TexString cap = os.release();
660 if (buffer().params().use_minted
661 || !contains(cap.str, from_ascii("\\label{")))
664 // blah1\label{blah2} blah3
666 // blah1 blah3},label={blah2
668 // caption={blah1 blah3},label={blah2}
670 // NOTE that } is not allowed in blah2.
671 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
672 string const new_cap("$1$3},label={$2");
673 // Remove potential \protect'ion of \label.
674 docstring capstr = subst(cap.str, from_ascii("\\protect\\label"),
675 from_ascii("\\label"));
676 // TexString validity: the substitution preserves the number of newlines.
677 // Moreover we assume that $2 does not contain newlines, so that the texrow
678 // information remains accurate.
679 // Replace '\n' with an improbable character from Private Use Area-A
680 // and then return to '\n' after the regex replacement.
681 capstr = subst(capstr, char_type('\n'), 0xffffd);
682 cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
683 0xffffd, char_type('\n'));
688 void InsetListings::string2params(string const & in,
689 InsetListingsParams & params)
691 params = InsetListingsParams();
694 istringstream data(in);
697 // discard "listings", which is only used to determine inset
703 string InsetListings::params2string(InsetListingsParams const & params)
706 data << "listings" << ' ';