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 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
124 string param_string = params().params();
125 // NOTE: I use {} to quote text, which is an experimental feature
126 // of the listings package (see page 25 of the manual)
127 bool const isInline = params().isInline();
128 bool const use_minted = buffer().params().use_minted;
129 string minted_language;
130 string float_placement;
131 bool const isfloat = params().isFloat();
132 if (use_minted && (isfloat || contains(param_string, "language="))) {
133 // Get float placement and/or language of the code,
134 // then remove the relative options.
135 vector<string> opts =
136 getVectorFromString(param_string, ",", false);
137 for (size_t i = 0; i < opts.size(); ++i) {
138 if (prefixIs(opts[i], "float")) {
139 if (prefixIs(opts[i], "float="))
140 float_placement = opts[i].substr(6);
141 opts.erase(opts.begin() + i--);
143 else if (prefixIs(opts[i], "language=")) {
144 minted_language = opts[i].substr(9);
145 opts.erase(opts.begin() + i--);
148 param_string = getStringFromVector(opts, ",");
150 // Minted needs a language specification
151 if (minted_language.empty())
152 minted_language = "TeX";
154 // get the paragraphs. We can not output them directly to given odocstream
155 // because we can not yet determine the delimiter character of \lstinline
158 ParagraphList::const_iterator par = paragraphs().begin();
159 ParagraphList::const_iterator end = paragraphs().end();
161 bool encoding_switched = false;
162 Encoding const * const save_enc = runparams.encoding;
163 // The listings package cannot deal with multi-byte-encoded
164 // glyphs, except if full-unicode aware backends
165 // such as XeTeX or LuaTeX are used, and with pLaTeX.
166 bool const multibyte_possible = use_minted || runparams.isFullUnicode()
167 || (buffer().params().encoding().package() == Encoding::japanese
168 && runparams.encoding->package() == Encoding::japanese);
170 if (!multibyte_possible && !runparams.encoding->hasFixedWidth()) {
171 // We need to switch to a singlebyte encoding, due to
172 // the restrictions of the listings package (see above).
173 // This needs to be consistent with
174 // LaTeXFeatures::getTClassI18nPreamble().
175 Language const * const outer_language =
176 (runparams.local_font != 0) ?
177 runparams.local_font->language()
178 : buffer().params().language;
179 // We try if there's a singlebyte encoding for the current
180 // language; if not, fall back to latin1.
181 Encoding const * const lstenc =
182 (outer_language->encoding()->hasFixedWidth()) ?
183 outer_language->encoding()
184 : encodings.fromLyXName("iso8859-1");
185 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
186 runparams.encoding = lstenc;
187 encoding_switched = true;
190 bool const captionfirst = !isfloat && par->isInset(0)
191 && par->getInset(0)->lyxCode() == CAPTION_CODE;
194 pos_type siz = par->size();
195 bool captionline = false;
196 for (pos_type i = 0; i < siz; ++i) {
197 if (i == 0 && par->isInset(i) && i + 1 == siz)
199 // ignore all struck out text and (caption) insets
200 if (par->isDeleted(i)
201 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
203 if (par->isInset(i)) {
204 // Currently, this can only be a quote inset
205 // that is output as plain quote here, but
206 // we use more generic code anyway.
207 otexstringstream ots;
208 OutputParams rp = runparams;
210 par->getInset(i)->latex(ots, rp);
214 char_type c = par->getChar(i);
215 // we can only output characters covered by the current
218 if (runparams.encoding->encodable(c))
220 else if (runparams.dryrun) {
221 code += "<" + _("LyX Warning: ")
222 + _("uncodable character") + " '";
223 code += docstring(1, c);
227 } catch (EncodingException & /* e */) {
228 if (runparams.dryrun) {
229 code += "<" + _("LyX Warning: ")
230 + _("uncodable character") + " '";
231 code += docstring(1, c);
238 // for the inline case, if there are multiple paragraphs
239 // they are simply joined. Otherwise, expect latex errors.
240 if (par != end && !isInline && !captionline)
244 static const docstring delimiters =
245 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
247 size_t pos = delimiters.find_first_not_of(code);
249 // This code piece contains all possible special character? !!!
250 // Replace ! with a warning message and use ! as delimiter.
251 if (pos == string::npos) {
252 docstring delim_error = "<" + _("LyX Warning: ")
253 + _("no more lstline delimiters available") + ">";
254 code = subst(code, from_ascii("!"), delim_error);
256 if (!runparams.dryrun && !runparams.silent) {
257 // FIXME: warning should be passed to the error dialog
258 frontend::Alert::warning(_("Running out of delimiters"),
259 _("For inline program listings, one character must be reserved\n"
260 "as a delimiter. One of the listings, however, uses all available\n"
261 "characters, so none is left for delimiting purposes.\n"
262 "For the time being, I have replaced '!' by a warning, but you\n"
263 "must investigate!"));
266 docstring const delim(1, delimiters[pos]);
268 os << "\\mintinline";
269 if (!param_string.empty())
270 os << "[" << from_utf8(param_string) << "]";
271 os << "{" << minted_language << "}";
274 if (!param_string.empty())
275 os << "[" << from_utf8(param_string) << "]";
276 else if (pos >= delimiters.find('Q'))
277 // We need to terminate the command before
281 os << delim << code << delim;
282 } else if (use_minted) {
283 OutputParams rp = runparams;
284 rp.moving_arg = true;
285 TexString caption = getCaption(rp);
287 os << breakln << "\\begin{listing}";
288 if (!float_placement.empty())
289 os << '[' << float_placement << "]";
290 } else if (captionfirst && !caption.str.empty()) {
291 os << breakln << "\\lyxmintcaption[t]{"
292 << move(caption) << "}\n";
294 os << breakln << "\\begin{minted}";
295 if (!param_string.empty())
296 os << "[" << param_string << "]";
297 os << "{" << minted_language << "}\n"
298 << code << breakln << "\\end{minted}\n";
300 if (!caption.str.empty())
301 os << "\\caption{" << move(caption) << "}\n";
302 os << "\\end{listing}\n";
303 } else if (!captionfirst && !caption.str.empty()) {
304 os << breakln << "\\lyxmintcaption[b]{"
305 << move(caption) << "}";
308 OutputParams rp = runparams;
309 rp.moving_arg = true;
310 TexString caption = getCaption(rp);
311 os << breakln << "\\begin{lstlisting}";
312 if (param_string.empty() && caption.str.empty())
318 if (!caption.str.empty()) {
319 os << "caption={" << move(caption) << '}';
320 if (!param_string.empty())
323 os << from_utf8(param_string) << "]\n";
325 os << code << breakln << "\\end{lstlisting}\n";
328 if (encoding_switched){
330 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
331 runparams.encoding = save_enc;
334 if (!uncodable.empty() && !runparams.silent) {
335 // issue a warning about omitted characters
336 // FIXME: should be passed to the error dialog
337 if (!multibyte_possible && !runparams.encoding->hasFixedWidth())
338 frontend::Alert::warning(_("Uncodable characters in listings inset"),
339 bformat(_("The following characters in one of the program listings are\n"
340 "not representable in the current encoding and have been omitted:\n%1$s.\n"
341 "This is due to a restriction of the listings package, which does\n"
342 "not support your encoding '%2$s'.\n"
343 "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
345 uncodable, _(runparams.encoding->guiName())));
347 frontend::Alert::warning(_("Uncodable characters in listings inset"),
348 bformat(_("The following characters in one of the program listings are\n"
349 "not representable in the current encoding and have been omitted:\n%1$s."),
355 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
357 odocstringstream ods;
358 XHTMLStream out(ods);
360 bool const isInline = params().isInline();
362 out << html::CompTag("br");
364 out << html::StartTag("div", "class='float-listings'");
365 docstring caption = getCaptionHTML(rp);
366 if (!caption.empty())
367 out << html::StartTag("div", "class='listings-caption'")
368 << XHTMLStream::ESCAPE_NONE
369 << caption << html::EndTag("div");
372 InsetLayout const & il = getLayout();
373 string const & tag = il.htmltag();
374 string attr = "class ='listings";
375 string const lang = params().getParamValue("language");
379 out << html::StartTag(tag, attr);
380 OutputParams newrp = rp;
381 newrp.html_disable_captions = true;
382 // We don't want to convert dashes here. That's the only conversion we
383 // do for XHTML, so this is safe.
384 newrp.pass_thru = true;
385 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
386 out << html::EndTag(tag);
389 out << html::CompTag("br");
390 // escaping will already have been done
391 os << XHTMLStream::ESCAPE_NONE << ods.str();
393 out << html::EndTag("div");
394 // In this case, this needs to be deferred, but we'll put it
395 // before anything the text itself deferred.
396 def = ods.str() + '\n' + def;
402 string InsetListings::contextMenuName() const
404 return "context-listings";
408 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
410 switch (cmd.action()) {
412 case LFUN_INSET_MODIFY: {
413 cur.recordUndoInset(this);
414 InsetListings::string2params(to_utf8(cmd.argument()), params());
418 case LFUN_INSET_DIALOG_UPDATE:
419 cur.bv().updateDialog("listings", params2string(params()));
423 InsetCaptionable::doDispatch(cur, cmd);
429 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
430 FuncStatus & status) const
432 switch (cmd.action()) {
433 case LFUN_INSET_MODIFY:
434 case LFUN_INSET_DIALOG_UPDATE:
435 status.setEnabled(true);
437 case LFUN_CAPTION_INSERT: {
438 // the inset outputs at most one caption
439 if (params().isInline() || getCaptionInset()) {
440 status.setEnabled(false);
445 return InsetCaptionable::getStatus(cur, cmd, status);
450 docstring const InsetListings::buttonLabel(BufferView const & bv) const
453 if (decoration() == InsetLayout::CLASSIC)
454 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
456 return getNewLabel(_("Listing"));
460 void InsetListings::validate(LaTeXFeatures & features) const
462 features.useInsetLayout(getLayout());
463 string param_string = params().params();
464 if (buffer().params().use_minted) {
465 features.require("minted");
466 OutputParams rp = features.runparams();
467 if (!params().isFloat() && !getCaption(rp).str.empty())
468 features.require("lyxmintcaption");
470 features.require("listings");
471 if (contains(param_string, "\\color"))
472 features.require("color");
474 InsetCaptionable::validate(features);
478 bool InsetListings::showInsetDialog(BufferView * bv) const
480 bv->showDialog("listings", params2string(params()),
481 const_cast<InsetListings *>(this));
486 TexString InsetListings::getCaption(OutputParams const & runparams) const
488 InsetCaption const * ins = getCaptionInset();
493 ins->getArgs(os, runparams);
494 ins->getArgument(os, runparams);
496 // TODO: The code below should be moved to support, and then the test
497 // in ../tests should be moved there as well.
499 // the caption may contain \label{} but the listings
500 // package prefer caption={}, label={}
501 TexString cap = os.release();
502 if (buffer().params().use_minted
503 || !contains(cap.str, from_ascii("\\label{")))
506 // blah1\label{blah2} blah3
508 // blah1 blah3},label={blah2
510 // caption={blah1 blah3},label={blah2}
512 // NOTE that } is not allowed in blah2.
513 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
514 string const new_cap("$1$3},label={$2");
515 // TexString validity: the substitution preserves the number of newlines.
516 // Moreover we assume that $2 does not contain newlines, so that the texrow
517 // information remains accurate.
518 cap.str = from_utf8(regex_replace(to_utf8(cap.str), reg, new_cap));
523 void InsetListings::string2params(string const & in,
524 InsetListingsParams & params)
526 params = InsetListingsParams();
529 istringstream data(in);
532 // discard "listings", which is only used to determine inset
538 string InsetListings::params2string(InsetListingsParams const & params)
541 data << "listings" << ' ';