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 if full-unicode aware backends
127 // such as XeTeX or LuaTeX are used, and with pLaTeX.
128 // Minted can deal with all encodings.
129 if (buffer().params().use_minted
130 || inner_enc->name() == "utf8-plain"
131 || (buffer().params().encoding().package() == Encoding::japanese
132 && inner_enc->package() == Encoding::japanese)
133 || inner_enc->hasFixedWidth())
136 // We try if there's a singlebyte encoding for the outer
137 // language; if not, fall back to latin1.
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 string minted_language;
151 string float_placement;
152 bool const isfloat = params().isFloat();
153 if (use_minted && (isfloat || contains(param_string, "language="))) {
154 // Get float placement and/or language of the code,
155 // then remove the relative options.
156 vector<string> opts =
157 getVectorFromString(param_string, ",", false);
158 for (size_t i = 0; i < opts.size(); ++i) {
159 if (prefixIs(opts[i], "float")) {
160 if (prefixIs(opts[i], "float="))
161 float_placement = opts[i].substr(6);
162 opts.erase(opts.begin() + i--);
164 else if (prefixIs(opts[i], "language=")) {
165 minted_language = opts[i].substr(9);
166 opts.erase(opts.begin() + i--);
169 param_string = getStringFromVector(opts, ",");
171 // Minted needs a language specification
172 if (minted_language.empty())
173 minted_language = "TeX";
175 // get the paragraphs. We can not output them directly to given odocstream
176 // because we can not yet determine the delimiter character of \lstinline
179 ParagraphList::const_iterator par = paragraphs().begin();
180 ParagraphList::const_iterator end = paragraphs().end();
182 bool encoding_switched = false;
183 Encoding const * const save_enc = runparams.encoding;
185 Encoding const * const outer_encoding =
186 (runparams.local_font != 0) ?
187 runparams.local_font->language()->encoding()
188 : buffer().params().language->encoding();
189 Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
191 // We need to switch to a singlebyte encoding, due to
192 // the restrictions of the listings package (see above).
193 // This needs to be consistent with
194 // LaTeXFeatures::getTClassI18nPreamble().
195 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
196 runparams.encoding = fixedlstenc;
197 encoding_switched = true;
200 bool const captionfirst = !isfloat && par->isInset(0)
201 && par->getInset(0)->lyxCode() == CAPTION_CODE;
204 pos_type const siz = par->size();
205 bool captionline = false;
206 for (pos_type i = 0; i < siz; ++i) {
207 if (i == 0 && par->isInset(i) && i + 1 == siz)
209 // ignore all struck out text and (caption) insets
210 if (par->isDeleted(i)
211 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
213 if (par->isInset(i)) {
214 // Currently, this can only be a quote inset
215 // that is output as plain quote here, but
216 // we use more generic code anyway.
217 otexstringstream ots;
218 OutputParams rp = runparams;
220 par->getInset(i)->latex(ots, rp);
224 char_type c = par->getChar(i);
225 // we can only output characters covered by the current
228 if (runparams.encoding->encodable(c))
230 else if (runparams.dryrun) {
231 code += "<" + _("LyX Warning: ")
232 + _("uncodable character") + " '";
233 code += docstring(1, c);
237 } catch (EncodingException & /* e */) {
238 if (runparams.dryrun) {
239 code += "<" + _("LyX Warning: ")
240 + _("uncodable character") + " '";
241 code += docstring(1, c);
248 // for the inline case, if there are multiple paragraphs
249 // they are simply joined. Otherwise, expect latex errors.
250 if (par != end && !isInline && !captionline)
254 static const docstring delimiters =
255 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
257 size_t pos = delimiters.find_first_not_of(code);
259 // This code piece contains all possible special character? !!!
260 // Replace ! with a warning message and use ! as delimiter.
261 if (pos == string::npos) {
262 docstring delim_error = "<" + _("LyX Warning: ")
263 + _("no more lstline delimiters available") + ">";
264 code = subst(code, from_ascii("!"), delim_error);
266 if (!runparams.dryrun && !runparams.silent) {
267 // FIXME: warning should be passed to the error dialog
268 frontend::Alert::warning(_("Running out of delimiters"),
269 _("For inline program listings, one character must be reserved\n"
270 "as a delimiter. One of the listings, however, uses all available\n"
271 "characters, so none is left for delimiting purposes.\n"
272 "For the time being, I have replaced '!' by a warning, but you\n"
273 "must investigate!"));
276 docstring const delim(1, delimiters[pos]);
278 os << "\\mintinline";
279 if (!param_string.empty())
280 os << "[" << from_utf8(param_string) << "]";
281 os << "{" << ascii_lowercase(minted_language) << "}";
284 if (!param_string.empty())
285 os << "[" << from_utf8(param_string) << "]";
286 else if (pos >= delimiters.find('Q'))
287 // We need to terminate the command before
291 os << delim << code << delim;
292 } else if (use_minted) {
293 OutputParams rp = runparams;
294 rp.moving_arg = true;
295 TexString caption = getCaption(rp);
297 os << breakln << "\\begin{listing}";
298 if (!float_placement.empty())
299 os << '[' << float_placement << "]";
300 } else if (captionfirst && !caption.str.empty()) {
301 os << breakln << "\\lyxmintcaption[t]{"
302 << move(caption) << "}\n";
304 os << breakln << "\\begin{minted}";
305 if (!param_string.empty())
306 os << "[" << param_string << "]";
307 os << "{" << ascii_lowercase(minted_language) << "}\n"
308 << code << breakln << "\\end{minted}\n";
310 if (!caption.str.empty())
311 os << "\\caption{" << move(caption) << "}\n";
312 os << "\\end{listing}\n";
313 } else if (!captionfirst && !caption.str.empty()) {
314 os << breakln << "\\lyxmintcaption[b]{"
315 << move(caption) << "}";
318 OutputParams rp = runparams;
319 rp.moving_arg = true;
320 TexString caption = getCaption(rp);
321 os << breakln << "\\begin{lstlisting}";
322 if (param_string.empty() && caption.str.empty())
328 if (!caption.str.empty()) {
329 os << "caption={" << move(caption) << '}';
330 if (!param_string.empty())
333 os << from_utf8(param_string) << "]\n";
335 os << code << breakln << "\\end{lstlisting}\n";
338 if (encoding_switched){
340 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
341 runparams.encoding = save_enc;
344 if (!uncodable.empty() && !runparams.silent) {
345 // issue a warning about omitted characters
346 // FIXME: should be passed to the error dialog
348 frontend::Alert::warning(_("Uncodable characters in listings inset"),
349 bformat(_("The following characters in one of the program listings are\n"
350 "not representable in the current encoding and have been omitted:\n%1$s.\n"
351 "This is due to a restriction of the listings package, which does\n"
352 "not support your encoding '%2$s'.\n"
353 "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
355 uncodable, _(runparams.encoding->guiName())));
357 frontend::Alert::warning(_("Uncodable characters in listings inset"),
358 bformat(_("The following characters in one of the program listings are\n"
359 "not representable in the current encoding and have been omitted:\n%1$s."),
365 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
367 odocstringstream ods;
368 XHTMLStream out(ods);
370 bool const isInline = params().isInline();
372 out << html::CompTag("br");
374 out << html::StartTag("div", "class='float-listings'");
375 docstring caption = getCaptionHTML(rp);
376 if (!caption.empty())
377 out << html::StartTag("div", "class='listings-caption'")
378 << XHTMLStream::ESCAPE_NONE
379 << caption << html::EndTag("div");
382 InsetLayout const & il = getLayout();
383 string const & tag = il.htmltag();
384 string attr = "class ='listings";
385 string const lang = params().getParamValue("language");
389 out << html::StartTag(tag, attr);
390 OutputParams newrp = rp;
391 newrp.html_disable_captions = true;
392 // We don't want to convert dashes here. That's the only conversion we
393 // do for XHTML, so this is safe.
394 newrp.pass_thru = true;
395 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
396 out << html::EndTag(tag);
399 out << html::CompTag("br");
400 // escaping will already have been done
401 os << XHTMLStream::ESCAPE_NONE << ods.str();
403 out << html::EndTag("div");
404 // In this case, this needs to be deferred, but we'll put it
405 // before anything the text itself deferred.
406 def = ods.str() + '\n' + def;
412 string InsetListings::contextMenuName() const
414 return "context-listings";
418 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
420 switch (cmd.action()) {
422 case LFUN_INSET_MODIFY: {
423 cur.recordUndoInset(this);
424 InsetListings::string2params(to_utf8(cmd.argument()), params());
428 case LFUN_INSET_DIALOG_UPDATE:
429 cur.bv().updateDialog("listings", params2string(params()));
433 InsetCaptionable::doDispatch(cur, cmd);
439 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
440 FuncStatus & status) const
442 switch (cmd.action()) {
443 case LFUN_INSET_MODIFY:
444 case LFUN_INSET_DIALOG_UPDATE:
445 status.setEnabled(true);
447 case LFUN_CAPTION_INSERT: {
448 // the inset outputs at most one caption
449 if (params().isInline() || getCaptionInset()) {
450 status.setEnabled(false);
456 return InsetCaptionable::getStatus(cur, cmd, status);
461 docstring const InsetListings::buttonLabel(BufferView const & bv) const
464 if (decoration() == InsetLayout::CLASSIC)
465 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
467 return getNewLabel(_("Listing"));
471 void InsetListings::validate(LaTeXFeatures & features) const
473 features.useInsetLayout(getLayout());
474 string param_string = params().params();
475 if (buffer().params().use_minted) {
476 features.require("minted");
477 OutputParams rp = features.runparams();
478 if (!params().isFloat() && !getCaption(rp).str.empty())
479 features.require("lyxmintcaption");
481 features.require("listings");
482 if (contains(param_string, "\\color"))
483 features.require("color");
485 InsetCaptionable::validate(features);
489 bool InsetListings::showInsetDialog(BufferView * bv) const
491 bv->showDialog("listings", params2string(params()),
492 const_cast<InsetListings *>(this));
497 TexString InsetListings::getCaption(OutputParams const & runparams) const
499 InsetCaption const * ins = getCaptionInset();
504 ins->getArgs(os, runparams);
505 ins->getArgument(os, runparams);
507 // TODO: The code below should be moved to support, and then the test
508 // in ../tests should be moved there as well.
510 // the caption may contain \label{} but the listings
511 // package prefer caption={}, label={}
512 TexString cap = os.release();
513 if (buffer().params().use_minted
514 || !contains(cap.str, from_ascii("\\label{")))
517 // blah1\label{blah2} blah3
519 // blah1 blah3},label={blah2
521 // caption={blah1 blah3},label={blah2}
523 // NOTE that } is not allowed in blah2.
524 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
525 string const new_cap("$1$3},label={$2");
526 // TexString validity: the substitution preserves the number of newlines.
527 // Moreover we assume that $2 does not contain newlines, so that the texrow
528 // information remains accurate.
529 // Replace '\n' with an improbable character from Private Use Area-A
530 // and then return to '\n' after the regex replacement.
531 docstring const capstr = subst(cap.str, char_type('\n'), 0xffffd);
532 cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
533 0xffffd, char_type('\n'));
538 void InsetListings::string2params(string const & in,
539 InsetListingsParams & params)
541 params = InsetListingsParams();
544 istringstream data(in);
547 // discard "listings", which is only used to determine inset
553 string InsetListings::params2string(InsetListingsParams const & params)
556 data << "listings" << ' ';