]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Wrap rotated cells with linebreaks in varwidth
[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 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
123                                                Encoding const * outer_enc) const
124 {
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())
134                 return 0;
135
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");
140 }
141
142
143 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
144 {
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--);
163                         }
164                         else if (prefixIs(opts[i], "language=")) {
165                                 minted_language = opts[i].substr(9);
166                                 opts.erase(opts.begin() + i--);
167                         }
168                 }
169                 param_string = getStringFromVector(opts, ",");
170         }
171         // Minted needs a language specification
172         if (minted_language.empty())
173                 minted_language = "TeX";
174
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
177         docstring code;
178         docstring uncodable;
179         ParagraphList::const_iterator par = paragraphs().begin();
180         ParagraphList::const_iterator end = paragraphs().end();
181
182         bool encoding_switched = false;
183         Encoding const * const save_enc = runparams.encoding;
184
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);
190         if (fixedlstenc) {
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                 // We need to put this into a group in order to prevent encoding leaks
196                 // (happens with cprotect).
197                 os << "\\bgroup";
198                 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
199                 runparams.encoding = fixedlstenc;
200                 encoding_switched = true;
201         }
202
203         bool const captionfirst = !isfloat && par->isInset(0)
204                                 && par->getInset(0)->lyxCode() == CAPTION_CODE;
205
206         while (par != end) {
207                 pos_type const siz = par->size();
208                 bool captionline = false;
209                 for (pos_type i = 0; i < siz; ++i) {
210                         if (i == 0 && par->isInset(i) && i + 1 == siz)
211                                 captionline = true;
212                         // ignore all struck out text and (caption) insets
213                         if (par->isDeleted(i)
214                             || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
215                                 continue;
216                         if (par->isInset(i)) {
217                                 // Currently, this can only be a quote inset
218                                 // that is output as plain quote here, but
219                                 // we use more generic code anyway.
220                                 otexstringstream ots;
221                                 OutputParams rp = runparams;
222                                 rp.pass_thru = true;
223                                 par->getInset(i)->latex(ots, rp);
224                                 code += ots.str();
225                                 continue;
226                         }
227                         char_type c = par->getChar(i);
228                         // we can only output characters covered by the current
229                         // encoding!
230                         try {
231                                 if (runparams.encoding->encodable(c))
232                                         code += c;
233                                 else if (runparams.dryrun) {
234                                         code += "<" + _("LyX Warning: ")
235                                            + _("uncodable character") + " '";
236                                         code += docstring(1, c);
237                                         code += "'>";
238                                 } else
239                                         uncodable += c;
240                         } catch (EncodingException & /* e */) {
241                                 if (runparams.dryrun) {
242                                         code += "<" + _("LyX Warning: ")
243                                            + _("uncodable character") + " '";
244                                         code += docstring(1, c);
245                                         code += "'>";
246                                 } else
247                                         uncodable += c;
248                         }
249                 }
250                 ++par;
251                 // for the inline case, if there are multiple paragraphs
252                 // they are simply joined. Otherwise, expect latex errors.
253                 if (par != end && !isInline && !captionline)
254                         code += "\n";
255         }
256         if (isInline) {
257                 static const docstring delimiters =
258                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
259
260                 size_t pos = delimiters.find_first_not_of(code);
261
262                 // This code piece contains all possible special character? !!!
263                 // Replace ! with a warning message and use ! as delimiter.
264                 if (pos == string::npos) {
265                         docstring delim_error = "<" + _("LyX Warning: ")
266                                 + _("no more lstline delimiters available") + ">";
267                         code = subst(code, from_ascii("!"), delim_error);
268                         pos = 0;
269                         if (!runparams.dryrun && !runparams.silent) {
270                                 // FIXME: warning should be passed to the error dialog
271                                 frontend::Alert::warning(_("Running out of delimiters"),
272                                 _("For inline program listings, one character must be reserved\n"
273                                   "as a delimiter. One of the listings, however, uses all available\n"
274                                   "characters, so none is left for delimiting purposes.\n"
275                                   "For the time being, I have replaced '!' by a warning, but you\n"
276                                   "must investigate!"));
277                         }
278                 }
279                 docstring const delim(1, delimiters[pos]);
280                 if (use_minted) {
281                         os << "\\mintinline";
282                         if (!param_string.empty())
283                                 os << "[" << from_utf8(param_string) << "]";
284                         os << "{" << ascii_lowercase(minted_language) << "}";
285                 } else {
286                         os << "\\lstinline";
287                         if (!param_string.empty())
288                                 os << "[" << from_utf8(param_string) << "]";
289                         else if (pos >= delimiters.find('Q'))
290                                 // We need to terminate the command before
291                                 // the delimiter
292                                 os << " ";
293                 }
294                 os << delim << code << delim;
295         } else if (use_minted) {
296                 OutputParams rp = runparams;
297                 rp.moving_arg = true;
298                 TexString caption = getCaption(rp);
299                 if (isfloat) {
300                         os << breakln << "\\begin{listing}";
301                         if (!float_placement.empty())
302                                 os << '[' << float_placement << "]";
303                 } else if (captionfirst && !caption.str.empty()) {
304                         os << breakln << "\\lyxmintcaption[t]{"
305                            << move(caption) << "}\n";
306                 }
307                 os << breakln << "\\begin{minted}";
308                 if (!param_string.empty())
309                         os << "[" << param_string << "]";
310                 os << "{" << ascii_lowercase(minted_language) << "}\n"
311                    << code << breakln << "\\end{minted}\n";
312                 if (isfloat) {
313                         if (!caption.str.empty())
314                                 os << "\\caption{" << move(caption) << "}\n";
315                         os << "\\end{listing}\n";
316                 } else if (!captionfirst && !caption.str.empty()) {
317                         os << breakln << "\\lyxmintcaption[b]{"
318                            << move(caption) << "}";
319                 }
320         } else {
321                 OutputParams rp = runparams;
322                 rp.moving_arg = true;
323                 TexString caption = getCaption(rp);
324                 os << breakln << "\\begin{lstlisting}";
325                 if (param_string.empty() && caption.str.empty())
326                         os << "\n";
327                 else {
328                         if (!runparams.nice)
329                                 os << safebreakln;
330                         os << "[";
331                         if (!caption.str.empty()) {
332                                 os << "caption={" << move(caption) << '}';
333                                 if (!param_string.empty())
334                                         os << ',';
335                         }
336                         os << from_utf8(param_string) << "]\n";
337                 }
338                 os << code << breakln << "\\end{lstlisting}\n";
339         }
340
341         if (encoding_switched){
342                 // Switch back
343                 switchEncoding(os.os(), buffer().params(),
344                                runparams, *save_enc, true, true);
345                 os << "\\egroup" << breakln;
346                 runparams.encoding = save_enc;
347         }
348
349         if (!uncodable.empty() && !runparams.silent) {
350                 // issue a warning about omitted characters
351                 // FIXME: should be passed to the error dialog
352                 if (fixedlstenc)
353                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
354                                 bformat(_("The following characters in one of the program listings are\n"
355                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
356                                           "This is due to a restriction of the listings package, which does\n"
357                                           "not support your encoding '%2$s'.\n"
358                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
359                                           "might help."),
360                                 uncodable, _(runparams.encoding->guiName())));
361                 else
362                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
363                                 bformat(_("The following characters in one of the program listings are\n"
364                                           "not representable in the current encoding and have been omitted:\n%1$s."),
365                                 uncodable));
366         }
367 }
368
369
370 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
371 {
372         odocstringstream ods;
373         XHTMLStream out(ods);
374
375         bool const isInline = params().isInline();
376         if (isInline)
377                 out << html::CompTag("br");
378         else {
379                 out << html::StartTag("div", "class='float-listings'");
380                 docstring caption = getCaptionHTML(rp);
381                 if (!caption.empty())
382                         out << html::StartTag("div", "class='listings-caption'")
383                             << XHTMLStream::ESCAPE_NONE
384                             << caption << html::EndTag("div");
385         }
386
387         InsetLayout const & il = getLayout();
388         string const & tag = il.htmltag();
389         string attr = "class ='listings";
390         string const lang = params().getParamValue("language");
391         if (!lang.empty())
392                 attr += " " + lang;
393         attr += "'";
394         out << html::StartTag(tag, attr);
395         OutputParams newrp = rp;
396         newrp.html_disable_captions = true;
397         // We don't want to convert dashes here. That's the only conversion we
398         // do for XHTML, so this is safe.
399         newrp.pass_thru = true;
400         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
401         out << html::EndTag(tag);
402
403         if (isInline) {
404                 out << html::CompTag("br");
405                 // escaping will already have been done
406                 os << XHTMLStream::ESCAPE_NONE << ods.str();
407         } else {
408                 out << html::EndTag("div");
409                 // In this case, this needs to be deferred, but we'll put it
410                 // before anything the text itself deferred.
411                 def = ods.str() + '\n' + def;
412         }
413         return def;
414 }
415
416
417 string InsetListings::contextMenuName() const
418 {
419         return "context-listings";
420 }
421
422
423 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
424 {
425         switch (cmd.action()) {
426
427         case LFUN_INSET_MODIFY: {
428                 cur.recordUndoInset(this);
429                 InsetListings::string2params(to_utf8(cmd.argument()), params());
430                 break;
431         }
432
433         case LFUN_INSET_DIALOG_UPDATE:
434                 cur.bv().updateDialog("listings", params2string(params()));
435                 break;
436
437         default:
438                 InsetCaptionable::doDispatch(cur, cmd);
439                 break;
440         }
441 }
442
443
444 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
445         FuncStatus & status) const
446 {
447         switch (cmd.action()) {
448                 case LFUN_INSET_MODIFY:
449                 case LFUN_INSET_DIALOG_UPDATE:
450                         status.setEnabled(true);
451                         return true;
452                 case LFUN_CAPTION_INSERT: {
453                         // the inset outputs at most one caption
454                         if (params().isInline() || getCaptionInset()) {
455                                 status.setEnabled(false);
456                                 return true;
457                         }
458                 }
459                 // fall through
460                 default:
461                         return InsetCaptionable::getStatus(cur, cmd, status);
462         }
463 }
464
465
466 docstring const InsetListings::buttonLabel(BufferView const & bv) const
467 {
468         // FIXME UNICODE
469         if (decoration() == InsetLayout::CLASSIC)
470                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
471         else
472                 return getNewLabel(_("Listing"));
473 }
474
475
476 void InsetListings::validate(LaTeXFeatures & features) const
477 {
478         features.useInsetLayout(getLayout());
479         string param_string = params().params();
480         if (buffer().params().use_minted) {
481                 features.require("minted");
482                 OutputParams rp = features.runparams();
483                 if (!params().isFloat() && !getCaption(rp).str.empty())
484                         features.require("lyxmintcaption");
485         } else {
486                 features.require("listings");
487                 if (contains(param_string, "\\color"))
488                         features.require("color");
489         }
490         InsetCaptionable::validate(features);
491 }
492
493
494 bool InsetListings::showInsetDialog(BufferView * bv) const
495 {
496         bv->showDialog("listings", params2string(params()),
497                 const_cast<InsetListings *>(this));
498         return true;
499 }
500
501
502 TexString InsetListings::getCaption(OutputParams const & runparams) const
503 {
504         InsetCaption const * ins = getCaptionInset();
505         if (ins == 0)
506                 return TexString();
507
508         otexstringstream os;
509         ins->getArgs(os, runparams);
510         ins->getArgument(os, runparams);
511
512         // TODO: The code below should be moved to support, and then the test
513         //       in ../tests should be moved there as well.
514
515         // the caption may contain \label{} but the listings
516         // package prefer caption={}, label={}
517         TexString cap = os.release();
518         if (buffer().params().use_minted
519             || !contains(cap.str, from_ascii("\\label{")))
520                 return cap;
521         // convert from
522         //     blah1\label{blah2} blah3
523         // to
524         //     blah1 blah3},label={blah2
525         // to form options
526         //     caption={blah1 blah3},label={blah2}
527         //
528         // NOTE that } is not allowed in blah2.
529         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
530         string const new_cap("$1$3},label={$2");
531         // TexString validity: the substitution preserves the number of newlines.
532         // Moreover we assume that $2 does not contain newlines, so that the texrow
533         // information remains accurate.
534         // Replace '\n' with an improbable character from Private Use Area-A
535         // and then return to '\n' after the regex replacement.
536         docstring const capstr = subst(cap.str, char_type('\n'), 0xffffd);
537         cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
538                         0xffffd, char_type('\n'));
539         return cap;
540 }
541
542
543 void InsetListings::string2params(string const & in,
544                                    InsetListingsParams & params)
545 {
546         params = InsetListingsParams();
547         if (in.empty())
548                 return;
549         istringstream data(in);
550         Lexer lex;
551         lex.setStream(data);
552         // discard "listings", which is only used to determine inset
553         lex.next();
554         params.read(lex);
555 }
556
557
558 string InsetListings::params2string(InsetListingsParams const & params)
559 {
560         ostringstream data;
561         data << "listings" << ' ';
562         params.write(data);
563         return data.str();
564 }
565
566
567 } // namespace lyx