]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Add suffixed lyxconvert to cmake build.
[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 "Counters.h"
20 #include "Cursor.h"
21 #include "DispatchResult.h"
22 #include "Encoding.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetCaption.h"
26 #include "Language.h"
27 #include "LaTeXFeatures.h"
28 #include "Lexer.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "TextClass.h"
33 #include "TexRow.h"
34 #include "texstream.h"
35
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"
41
42 #include "frontends/alert.h"
43 #include "frontends/Application.h"
44
45 #include "support/regex.h"
46
47 #include <sstream>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace lyx {
53
54
55 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
56         : InsetCaptionable(buf,"listing")
57 {
58         params_.setMinted(buffer().params().use_minted);
59         status_ = par.status();
60 }
61
62
63 InsetListings::~InsetListings()
64 {
65         hideDialogs("listings", this);
66 }
67
68
69 Inset::DisplayType InsetListings::display() const
70 {
71         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
72 }
73
74
75 docstring InsetListings::layoutName() const
76 {
77         if (buffer().params().use_minted)
78                 return from_ascii("MintedListings");
79         else
80                 return from_ascii("Listings");
81 }
82
83
84 void InsetListings::write(ostream & os) const
85 {
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();
90         if (!opt.empty())
91                 os << "lstparams \"" << opt << "\"\n";
92         if (par.isInline())
93                 os << "inline true\n";
94         else
95                 os << "inline false\n";
96         InsetCaptionable::write(os);
97 }
98
99
100 void InsetListings::read(Lexer & lex)
101 {
102         while (lex.isOK()) {
103                 lex.next();
104                 string token = lex.getString();
105                 if (token == "lstparams") {
106                         lex.next();
107                         string const value = lex.getString();
108                         params().fromEncodedString(value);
109                 } else if (token == "inline") {
110                         lex.next();
111                         params().setInline(lex.getBool());
112                 } else {
113                         // no special option, push back 'status' etc
114                         lex.pushToken(token);
115                         break;
116                 }
117         }
118         InsetCaptionable::read(lex);
119 }
120
121
122 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
123 {
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--);
142                         }
143                         else if (prefixIs(opts[i], "language=")) {
144                                 minted_language = opts[i].substr(9);
145                                 opts.erase(opts.begin() + i--);
146                         }
147                 }
148                 param_string = getStringFromVector(opts, ",");
149         }
150         // Minted needs a language specification
151         if (minted_language.empty())
152                 minted_language = "TeX";
153
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
156         docstring code;
157         docstring uncodable;
158         ParagraphList::const_iterator par = paragraphs().begin();
159         ParagraphList::const_iterator end = paragraphs().end();
160
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);
169
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;
188         }
189
190         bool const captionfirst = !isfloat && par->isInset(0)
191                                 && par->getInset(0)->lyxCode() == CAPTION_CODE;
192
193         while (par != end) {
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)
198                                 captionline = true;
199                         // ignore all struck out text and (caption) insets
200                         if (par->isDeleted(i)
201                             || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
202                                 continue;
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;
209                                 rp.pass_thru = true;
210                                 par->getInset(i)->latex(ots, rp);
211                                 code += ots.str();
212                                 continue;
213                         }
214                         char_type c = par->getChar(i);
215                         // we can only output characters covered by the current
216                         // encoding!
217                         try {
218                                 if (runparams.encoding->encodable(c))
219                                         code += c;
220                                 else if (runparams.dryrun) {
221                                         code += "<" + _("LyX Warning: ")
222                                            + _("uncodable character") + " '";
223                                         code += docstring(1, c);
224                                         code += "'>";
225                                 } else
226                                         uncodable += c;
227                         } catch (EncodingException & /* e */) {
228                                 if (runparams.dryrun) {
229                                         code += "<" + _("LyX Warning: ")
230                                            + _("uncodable character") + " '";
231                                         code += docstring(1, c);
232                                         code += "'>";
233                                 } else
234                                         uncodable += c;
235                         }
236                 }
237                 ++par;
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)
241                         code += "\n";
242         }
243         if (isInline) {
244                 static const docstring delimiters =
245                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
246
247                 size_t pos = delimiters.find_first_not_of(code);
248
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);
255                         pos = 0;
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!"));
264                         }
265                 }
266                 docstring const delim(1, delimiters[pos]);
267                 if (use_minted) {
268                         os << "\\mintinline";
269                         if (!param_string.empty())
270                                 os << "[" << from_utf8(param_string) << "]";
271                         os << "{" << ascii_lowercase(minted_language) << "}";
272                 } else {
273                         os << "\\lstinline";
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
278                                 // the delimiter
279                                 os << " ";
280                 }
281                 os << delim << code << delim;
282         } else if (use_minted) {
283                 OutputParams rp = runparams;
284                 rp.moving_arg = true;
285                 TexString caption = getCaption(rp);
286                 if (isfloat) {
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";
293                 }
294                 os << breakln << "\\begin{minted}";
295                 if (!param_string.empty())
296                         os << "[" << param_string << "]";
297                 os << "{" << ascii_lowercase(minted_language) << "}\n"
298                    << code << breakln << "\\end{minted}\n";
299                 if (isfloat) {
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) << "}";
306                 }
307         } else {
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())
313                         os << "\n";
314                 else {
315                         if (!runparams.nice)
316                                 os << safebreakln;
317                         os << "[";
318                         if (!caption.str.empty()) {
319                                 os << "caption={" << move(caption) << '}';
320                                 if (!param_string.empty())
321                                         os << ',';
322                         }
323                         os << from_utf8(param_string) << "]\n";
324                 }
325                 os << code << breakln << "\\end{lstlisting}\n";
326         }
327
328         if (encoding_switched){
329                 // Switch back
330                 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
331                 runparams.encoding = save_enc;
332         }
333
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"
344                                           "might help."),
345                                 uncodable, _(runparams.encoding->guiName())));
346                 else
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."),
350                                 uncodable));
351         }
352 }
353
354
355 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
356 {
357         odocstringstream ods;
358         XHTMLStream out(ods);
359
360         bool const isInline = params().isInline();
361         if (isInline)
362                 out << html::CompTag("br");
363         else {
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");
370         }
371
372         InsetLayout const & il = getLayout();
373         string const & tag = il.htmltag();
374         string attr = "class ='listings";
375         string const lang = params().getParamValue("language");
376         if (!lang.empty())
377                 attr += " " + lang;
378         attr += "'";
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);
387
388         if (isInline) {
389                 out << html::CompTag("br");
390                 // escaping will already have been done
391                 os << XHTMLStream::ESCAPE_NONE << ods.str();
392         } else {
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;
397         }
398         return def;
399 }
400
401
402 string InsetListings::contextMenuName() const
403 {
404         return "context-listings";
405 }
406
407
408 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
409 {
410         switch (cmd.action()) {
411
412         case LFUN_INSET_MODIFY: {
413                 cur.recordUndoInset(this);
414                 InsetListings::string2params(to_utf8(cmd.argument()), params());
415                 break;
416         }
417
418         case LFUN_INSET_DIALOG_UPDATE:
419                 cur.bv().updateDialog("listings", params2string(params()));
420                 break;
421
422         default:
423                 InsetCaptionable::doDispatch(cur, cmd);
424                 break;
425         }
426 }
427
428
429 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
430         FuncStatus & status) const
431 {
432         switch (cmd.action()) {
433                 case LFUN_INSET_MODIFY:
434                 case LFUN_INSET_DIALOG_UPDATE:
435                         status.setEnabled(true);
436                         return true;
437                 case LFUN_CAPTION_INSERT: {
438                         // the inset outputs at most one caption
439                         if (params().isInline() || getCaptionInset()) {
440                                 status.setEnabled(false);
441                                 return true;
442                         }
443                 }
444                 // fall through
445                 default:
446                         return InsetCaptionable::getStatus(cur, cmd, status);
447         }
448 }
449
450
451 docstring const InsetListings::buttonLabel(BufferView const & bv) const
452 {
453         // FIXME UNICODE
454         if (decoration() == InsetLayout::CLASSIC)
455                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
456         else
457                 return getNewLabel(_("Listing"));
458 }
459
460
461 void InsetListings::validate(LaTeXFeatures & features) const
462 {
463         features.useInsetLayout(getLayout());
464         string param_string = params().params();
465         if (buffer().params().use_minted) {
466                 features.require("minted");
467                 OutputParams rp = features.runparams();
468                 if (!params().isFloat() && !getCaption(rp).str.empty())
469                         features.require("lyxmintcaption");
470         } else {
471                 features.require("listings");
472                 if (contains(param_string, "\\color"))
473                         features.require("color");
474         }
475         InsetCaptionable::validate(features);
476 }
477
478
479 bool InsetListings::showInsetDialog(BufferView * bv) const
480 {
481         bv->showDialog("listings", params2string(params()),
482                 const_cast<InsetListings *>(this));
483         return true;
484 }
485
486
487 TexString InsetListings::getCaption(OutputParams const & runparams) const
488 {
489         InsetCaption const * ins = getCaptionInset();
490         if (ins == 0)
491                 return TexString();
492
493         otexstringstream os;
494         ins->getArgs(os, runparams);
495         ins->getArgument(os, runparams);
496
497         // TODO: The code below should be moved to support, and then the test
498         //       in ../tests should be moved there as well.
499
500         // the caption may contain \label{} but the listings
501         // package prefer caption={}, label={}
502         TexString cap = os.release();
503         if (buffer().params().use_minted
504             || !contains(cap.str, from_ascii("\\label{")))
505                 return cap;
506         // convert from
507         //     blah1\label{blah2} blah3
508         // to
509         //     blah1 blah3},label={blah2
510         // to form options
511         //     caption={blah1 blah3},label={blah2}
512         //
513         // NOTE that } is not allowed in blah2.
514         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
515         string const new_cap("$1$3},label={$2");
516         // TexString validity: the substitution preserves the number of newlines.
517         // Moreover we assume that $2 does not contain newlines, so that the texrow
518         // information remains accurate.
519         // Replace '\n' with an improbable character from Private Use Area-A
520         // and then return to '\n' after the regex replacement.
521         docstring const capstr = subst(cap.str, char_type('\n'), 0xffffd);
522         cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
523                         0xffffd, char_type('\n'));
524         return cap;
525 }
526
527
528 void InsetListings::string2params(string const & in,
529                                    InsetListingsParams & params)
530 {
531         params = InsetListingsParams();
532         if (in.empty())
533                 return;
534         istringstream data(in);
535         Lexer lex;
536         lex.setStream(data);
537         // discard "listings", which is only used to determine inset
538         lex.next();
539         params.read(lex);
540 }
541
542
543 string InsetListings::params2string(InsetListingsParams const & params)
544 {
545         ostringstream data;
546         data << "listings" << ' ';
547         params.write(data);
548         return data.str();
549 }
550
551
552 } // namespace lyx