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 "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetCaption.h"
27 #include "LaTeXFeatures.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "TextClass.h"
34 #include "texstream.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
40 #include "support/lassert.h"
42 #include "frontends/alert.h"
43 #include "frontends/Application.h"
45 #include "support/regex.h"
50 using namespace lyx::support;
55 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
56 : InsetCaptionable(buf,"listing")
58 params_.setMinted(buffer().params().use_minted);
59 status_ = par.status();
63 InsetListings::~InsetListings()
65 hideDialogs("listings", this);
69 Inset::DisplayType InsetListings::display() const
71 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
75 docstring InsetListings::layoutName() const
77 if (buffer().params().use_minted)
78 return from_ascii("MintedListings");
80 return from_ascii("Listings");
84 void InsetListings::write(ostream & os) const
86 os << "listings" << "\n";
87 InsetListingsParams const & par = params();
88 // parameter string is encoded to be a valid lyx token.
89 string opt = par.encodedString();
91 os << "lstparams \"" << opt << "\"\n";
93 os << "inline true\n";
95 os << "inline false\n";
96 InsetCaptionable::write(os);
100 void InsetListings::read(Lexer & lex)
104 string token = lex.getString();
105 if (token == "lstparams") {
107 string const value = lex.getString();
108 params().fromEncodedString(value);
109 } else if (token == "inline") {
111 params().setInline(lex.getBool());
113 // no special option, push back 'status' etc
114 lex.pushToken(token);
118 InsetCaptionable::read(lex);
122 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
123 Encoding const * outer_enc) const
125 // The listings package cannot deal with multi-byte-encoded
126 // glyphs, except for Xe/LuaTeX (with non-TeX fonts) or pLaTeX.
127 // Minted can deal with all encodings.
128 if (buffer().params().use_minted
129 || inner_enc->name() == "utf8-plain"
130 || inner_enc->package() == Encoding::japanese
131 || inner_enc->hasFixedWidth())
134 // We try if there's a singlebyte encoding for the outer
135 // language; if not, fall back to latin1.
136 // Power-users can set inputenc to utf8-plain to bypass this workaround
137 // and provide alternatives in the user-preamble.
138 return (outer_enc->hasFixedWidth()) ?
139 outer_enc : encodings.fromLyXName("iso8859-1");
143 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
145 string param_string = params().params();
146 // NOTE: I use {} to quote text, which is an experimental feature
147 // of the listings package (see page 25 of the manual)
148 bool const isInline = params().isInline();
149 bool const use_minted = buffer().params().use_minted;
150 static regex const reg1("(.*)(basicstyle=\\{)([^\\}]*)(\\\\ttfamily)([^\\}]*)(\\})(.*)");
151 static regex const reg2("(.*)(basicstyle=\\{)([^\\}]*)(\\\\rmfamily)([^\\}]*)(\\})(.*)");
152 static regex const reg3("(.*)(basicstyle=\\{)([^\\}]*)(\\\\sffamily)([^\\}]*)(\\})(.*)");
153 static regex const reg4("(.*)(basicstyle=\\{)([^\\}]*)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))([^\\}]*)(\\})(.*)");
154 static regex const reg5("(.*)(fontfamily=)(tt|sf|rm)(.*)");
155 static regex const reg6("(.*)(fontsize=\\{)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))(\\})(.*)");
157 // If params have been entered with "listings", and then the user switched to "minted",
158 // we have params that need to be translated.
159 // FIXME: We should use a backend-abstract syntax in listings params instead!
160 // Substitute fontstyle option
162 if (regex_match(param_string, sub, reg1))
163 param_string = sub.str(1) + "fontfamily=tt," + sub.str(2) + sub.str(3)
164 + sub.str(5) + sub.str(6) + sub.str(7);
165 if (regex_match(param_string, sub, reg2))
166 param_string = sub.str(1) + "fontfamily=rm," + sub.str(2) + sub.str(3)
167 + sub.str(5) + sub.str(6) + sub.str(7);
168 if (regex_match(param_string, sub, reg3))
169 param_string = sub.str(1) + "fontfamily=sf," + sub.str(2) + sub.str(3)
170 + sub.str(5) + sub.str(6) + sub.str(7);
171 // as well as fontsize option
172 if (regex_match(param_string, sub, reg4))
173 param_string = sub.str(1) + "fontsize={" + sub.str(4) + sub.str(3) + sub.str(7) + sub.str(8);
175 // And the same vice versa
176 // Substitute fontstyle option
179 if (regex_match(param_string, sub, reg5)) {
180 basicstyle = "\\" + sub.str(3) + "family";
181 param_string = sub.str(1) + sub.str(4);
183 // as well as fontsize option
184 if (regex_match(param_string, sub, reg6)) {
185 basicstyle += sub.str(3);
186 param_string = sub.str(1) + sub.str(6);
188 if (!basicstyle.empty())
189 param_string = rtrim(param_string, ",") + ",basicstyle={" + basicstyle + "}";
191 if (runparams.use_polyglossia && runparams.local_font->isRightToLeft()) {
192 // We need to use the *latin switches (#11554)
194 if (regex_match(param_string, sub, reg1))
195 param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
196 + "latin" + sub.str(5) + sub.str(6) + sub.str(7);
197 if (regex_match(param_string, sub, reg2))
198 param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
199 + "latin" + sub.str(5) + sub.str(6) + sub.str(7);
200 if (regex_match(param_string, sub, reg3))
201 param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
202 + "latin" + sub.str(5) + sub.str(6) + sub.str(7);
204 string minted_language;
205 string float_placement;
206 bool const isfloat = params().isFloat();
207 if (use_minted && (isfloat || contains(param_string, "language="))) {
208 // Get float placement and/or language of the code,
209 // then remove the relative options.
210 vector<string> opts =
211 getVectorFromString(param_string, ",", false);
212 for (size_t i = 0; i < opts.size(); ++i) {
213 if (prefixIs(opts[i], "float")) {
214 if (prefixIs(opts[i], "float="))
215 float_placement = opts[i].substr(6);
216 opts.erase(opts.begin() + int(i--));
218 else if (prefixIs(opts[i], "language=")) {
219 minted_language = opts[i].substr(9);
220 opts.erase(opts.begin() + int(i--));
223 param_string = getStringFromVector(opts, ",");
225 // Minted needs a language specification
226 if (minted_language.empty()) {
227 // If a language has been set globally, use that,
228 // otherwise use TeX by default
229 string const & blp = buffer().params().listings_params;
230 size_t start = blp.find("language=");
231 if (start != string::npos) {
232 start += strlen("language=");
233 size_t len = blp.find(",", start);
234 if (len != string::npos)
236 minted_language = blp.substr(start, len);
238 minted_language = "TeX";
241 // get the paragraphs. We can not output them directly to given odocstream
242 // because we can not yet determine the delimiter character of \lstinline
245 ParagraphList::const_iterator par = paragraphs().begin();
246 ParagraphList::const_iterator end = paragraphs().end();
248 bool encoding_switched = false;
249 Encoding const * const save_enc = runparams.encoding;
251 Encoding const * const outer_encoding =
252 (runparams.local_font != 0) ?
253 runparams.local_font->language()->encoding()
254 : buffer().params().language->encoding();
255 Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
257 // We need to switch to a singlebyte encoding, due to
258 // the restrictions of the listings package (see above).
259 // This needs to be consistent with
260 // LaTeXFeatures::getTClassI18nPreamble().
261 // We need to put this into a group in order to prevent encoding leaks
262 // (happens with cprotect).
264 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
265 runparams.encoding = fixedlstenc;
266 encoding_switched = true;
269 bool const captionfirst = !isfloat && par->isInset(0)
270 && par->getInset(0)->lyxCode() == CAPTION_CODE;
273 pos_type const siz = par->size();
274 bool captionline = false;
275 for (pos_type i = 0; i < siz; ++i) {
276 if (i == 0 && par->isInset(i) && i + 1 == siz)
278 // ignore all struck out text and (caption) insets
279 if (par->isDeleted(i)
280 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
282 if (par->isInset(i)) {
283 // Currently, this can only be a quote inset
284 // that is output as plain quote here, but
285 // we use more generic code anyway.
286 otexstringstream ots;
287 OutputParams rp = runparams;
289 par->getInset(i)->latex(ots, rp);
293 char_type c = par->getChar(i);
294 // we can only output characters covered by the current
297 if (runparams.encoding->encodable(c))
299 else if (runparams.dryrun) {
300 code += "<" + _("LyX Warning: ")
301 + _("uncodable character") + " '";
302 code += docstring(1, c);
306 } catch (EncodingException & /* e */) {
307 if (runparams.dryrun) {
308 code += "<" + _("LyX Warning: ")
309 + _("uncodable character") + " '";
310 code += docstring(1, c);
317 // for the inline case, if there are multiple paragraphs
318 // they are simply joined. Otherwise, expect latex errors.
319 if (par != end && !isInline && !captionline)
323 static const docstring delimiters =
324 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
326 size_t pos = delimiters.find_first_not_of(code);
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);
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!"));
345 docstring const delim(1, delimiters[pos]);
347 os << "\\mintinline";
348 if (!param_string.empty())
349 os << "[" << from_utf8(param_string) << "]";
350 os << "{" << ascii_lowercase(minted_language) << "}";
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
360 os << delim << code << delim;
361 } else if (use_minted) {
362 OutputParams rp = runparams;
363 rp.moving_arg = true;
364 TexString caption = getCaption(rp);
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";
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";
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) << "}";
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())
397 if (!caption.str.empty()) {
398 os << "caption={" << move(caption) << '}';
399 if (!param_string.empty())
402 os << from_utf8(param_string) << "]\n";
404 os << code << breakln << "\\end{lstlisting}\n";
407 if (encoding_switched){
409 switchEncoding(os.os(), buffer().params(),
410 runparams, *save_enc, true, true);
411 os << "\\egroup" << breakln;
412 runparams.encoding = save_enc;
415 if (!uncodable.empty() && !runparams.silent) {
416 // issue a warning about omitted characters
417 // FIXME: should be passed to the error dialog
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"
426 uncodable, _(runparams.encoding->guiName())));
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."),
436 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
438 odocstringstream ods;
439 XHTMLStream out(ods);
441 bool const isInline = params().isInline();
443 out << html::CompTag("br");
445 out << html::StartTag("div", "class='float-listings'");
446 docstring caption = getCaptionHTML(rp);
447 if (!caption.empty())
448 out << html::StartTag("div", "class='listings-caption'")
449 << XHTMLStream::ESCAPE_NONE
450 << caption << html::EndTag("div");
453 InsetLayout const & il = getLayout();
454 string const & tag = il.htmltag();
455 string attr = "class ='listings";
456 string const lang = params().getParamValue("language");
460 out << html::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 << html::EndTag(tag);
470 out << html::CompTag("br");
471 // escaping will already have been done
472 os << XHTMLStream::ESCAPE_NONE << ods.str();
474 out << html::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;
483 string InsetListings::contextMenuName() const
485 return "context-listings";
489 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
491 switch (cmd.action()) {
493 case LFUN_INSET_MODIFY: {
494 cur.recordUndoInset(this);
495 InsetListings::string2params(to_utf8(cmd.argument()), params());
499 case LFUN_INSET_DIALOG_UPDATE:
500 cur.bv().updateDialog("listings", params2string(params()));
504 InsetCaptionable::doDispatch(cur, cmd);
510 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
511 FuncStatus & status) const
513 switch (cmd.action()) {
514 case LFUN_INSET_MODIFY:
515 case LFUN_INSET_DIALOG_UPDATE:
516 status.setEnabled(true);
518 case LFUN_CAPTION_INSERT: {
519 // the inset outputs at most one caption
520 if (params().isInline() || getCaptionInset()) {
521 status.setEnabled(false);
527 return InsetCaptionable::getStatus(cur, cmd, status);
532 docstring const InsetListings::buttonLabel(BufferView const & bv) const
535 if (decoration() == InsetLayout::CLASSIC)
536 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
538 return getNewLabel(_("Listing"));
542 void InsetListings::validate(LaTeXFeatures & features) const
544 features.useInsetLayout(getLayout());
545 string param_string = params().params();
546 if (buffer().params().use_minted) {
547 features.require("minted");
548 OutputParams rp = features.runparams();
549 if (!params().isFloat() && !getCaption(rp).str.empty())
550 features.require("lyxmintcaption");
551 if (features.usePolyglossia() && features.hasRTLLanguage())
552 // minted loads color, but color must be loaded before bidi
553 // (i.e., polyglossia)
554 features.require("color");
556 features.require("listings");
557 if (contains(param_string, "\\color"))
558 features.require("color");
560 InsetCaptionable::validate(features);
564 bool InsetListings::showInsetDialog(BufferView * bv) const
566 bv->showDialog("listings", params2string(params()),
567 const_cast<InsetListings *>(this));
572 TexString InsetListings::getCaption(OutputParams const & runparams) const
574 InsetCaption const * ins = getCaptionInset();
579 ins->getArgs(os, runparams);
580 ins->getArgument(os, runparams);
582 // TODO: The code below should be moved to support, and then the test
583 // in ../tests should be moved there as well.
585 // the caption may contain \label{} but the listings
586 // package prefer caption={}, label={}
587 TexString cap = os.release();
588 if (buffer().params().use_minted
589 || !contains(cap.str, from_ascii("\\label{")))
592 // blah1\label{blah2} blah3
594 // blah1 blah3},label={blah2
596 // caption={blah1 blah3},label={blah2}
598 // NOTE that } is not allowed in blah2.
599 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
600 string const new_cap("$1$3},label={$2");
601 // Remove potential \protect'ion of \label.
602 docstring capstr = subst(cap.str, from_ascii("\\protect\\label"),
603 from_ascii("\\label"));
604 // TexString validity: the substitution preserves the number of newlines.
605 // Moreover we assume that $2 does not contain newlines, so that the texrow
606 // information remains accurate.
607 // Replace '\n' with an improbable character from Private Use Area-A
608 // and then return to '\n' after the regex replacement.
609 capstr = subst(capstr, char_type('\n'), 0xffffd);
610 cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
611 0xffffd, char_type('\n'));
616 void InsetListings::string2params(string const & in,
617 InsetListingsParams & params)
619 params = InsetListingsParams();
622 istringstream data(in);
625 // discard "listings", which is only used to determine inset
631 string InsetListings::params2string(InsetListingsParams const & params)
634 data << "listings" << ' ';