]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
a92c09525c9f0dc8616b4d551e7fa6fc40817e7b
[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         status_ = par.status();
59 }
60
61
62 InsetListings::~InsetListings()
63 {
64         hideDialogs("listings", this);
65 }
66
67
68 Inset::DisplayType InsetListings::display() const
69 {
70         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
71 }
72
73
74 void InsetListings::write(ostream & os) const
75 {
76         os << "listings" << "\n";
77         InsetListingsParams const & par = params();
78         // parameter string is encoded to be a valid lyx token.
79         string opt = par.encodedString();
80         if (!opt.empty())
81                 os << "lstparams \"" << opt << "\"\n";
82         if (par.isInline())
83                 os << "inline true\n";
84         else
85                 os << "inline false\n";
86         InsetCaptionable::write(os);
87 }
88
89
90 void InsetListings::read(Lexer & lex)
91 {
92         while (lex.isOK()) {
93                 lex.next();
94                 string token = lex.getString();
95                 if (token == "lstparams") {
96                         lex.next();
97                         string const value = lex.getString();
98                         params().fromEncodedString(value);
99                 } else if (token == "inline") {
100                         lex.next();
101                         params().setInline(lex.getBool());
102                 } else {
103                         // no special option, push back 'status' etc
104                         lex.pushToken(token);
105                         break;
106                 }
107         }
108         InsetCaptionable::read(lex);
109 }
110
111
112 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
113 {
114         string param_string = params().params();
115         // NOTE: I use {} to quote text, which is an experimental feature
116         // of the listings package (see page 25 of the manual)
117         bool const isInline = params().isInline();
118         // get the paragraphs. We can not output them directly to given odocstream
119         // because we can not yet determine the delimiter character of \lstinline
120         docstring code;
121         docstring uncodable;
122         ParagraphList::const_iterator par = paragraphs().begin();
123         ParagraphList::const_iterator end = paragraphs().end();
124
125         bool encoding_switched = false;
126         Encoding const * const save_enc = runparams.encoding;
127         // The listings package cannot deal with multi-byte-encoded
128         // glyphs, except if full-unicode aware backends
129         // such as XeTeX or LuaTeX are used, and with pLaTeX.
130         bool const multibyte_possible = runparams.isFullUnicode()
131             || (buffer().params().encoding().package() == Encoding::japanese
132                 && runparams.encoding->package() == Encoding::japanese);
133
134         if (!multibyte_possible && !runparams.encoding->hasFixedWidth()) {
135                 // We need to switch to a singlebyte encoding, due to
136                 // the restrictions of the listings package (see above).
137                 // This needs to be consistent with
138                 // LaTeXFeatures::getTClassI18nPreamble().
139                 Language const * const outer_language =
140                         (runparams.local_font != 0) ?
141                                 runparams.local_font->language()
142                                 : buffer().params().language;
143                 // We try if there's a singlebyte encoding for the current
144                 // language; if not, fall back to latin1.
145                 Encoding const * const lstenc =
146                         (outer_language->encoding()->hasFixedWidth()) ?
147                                 outer_language->encoding()
148                                 : encodings.fromLyXName("iso8859-1");
149                 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
150                 runparams.encoding = lstenc;
151                 encoding_switched = true;
152         }
153
154         while (par != end) {
155                 pos_type siz = par->size();
156                 bool captionline = false;
157                 for (pos_type i = 0; i < siz; ++i) {
158                         if (i == 0 && par->isInset(i) && i + 1 == siz)
159                                 captionline = true;
160                         // ignore all struck out text and (caption) insets
161                         if (par->isDeleted(i) || par->isInset(i))
162                                 continue;
163                         char_type c = par->getChar(i);
164                         // we can only output characters covered by the current
165                         // encoding!
166                         try {
167                                 if (runparams.encoding->encodable(c))
168                                         code += c;
169                                 else if (runparams.dryrun) {
170                                         code += "<" + _("LyX Warning: ")
171                                            + _("uncodable character") + " '";
172                                         code += docstring(1, c);
173                                         code += "'>";
174                                 } else
175                                         uncodable += c;
176                         } catch (EncodingException & /* e */) {
177                                 if (runparams.dryrun) {
178                                         code += "<" + _("LyX Warning: ")
179                                            + _("uncodable character") + " '";
180                                         code += docstring(1, c);
181                                         code += "'>";
182                                 } else
183                                         uncodable += c;
184                         }
185                 }
186                 ++par;
187                 // for the inline case, if there are multiple paragraphs
188                 // they are simply joined. Otherwise, expect latex errors.
189                 if (par != end && !isInline && !captionline)
190                         code += "\n";
191         }
192         if (isInline) {
193                 static const docstring delimiters =
194                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
195
196                 size_t pos = delimiters.find_first_not_of(code);
197
198                 // This code piece contains all possible special character? !!!
199                 // Replace ! with a warning message and use ! as delimiter.
200                 if (pos == string::npos) {
201                         docstring delim_error = "<" + _("LyX Warning: ")
202                                 + _("no more lstline delimiters available") + ">";
203                         code = subst(code, from_ascii("!"), delim_error);
204                         pos = 0;
205                         if (!runparams.dryrun && !runparams.silent) {
206                                 // FIXME: warning should be passed to the error dialog
207                                 frontend::Alert::warning(_("Running out of delimiters"),
208                                 _("For inline program listings, one character must be reserved\n"
209                                   "as a delimiter. One of the listings, however, uses all available\n"
210                                   "characters, so none is left for delimiting purposes.\n"
211                                   "For the time being, I have replaced '!' by a warning, but you\n"
212                                   "must investigate!"));
213                         }
214                 }
215                 docstring const delim(1, delimiters[pos]);
216                 os << "\\lstinline";
217                 if (!param_string.empty())
218                         os << "[" << from_utf8(param_string) << "]";
219                 else if (pos >= delimiters.find('Q'))
220                         // We need to terminate the command before the delimiter
221                         os << " ";
222                 os << delim << code << delim;
223         } else {
224                 OutputParams rp = runparams;
225                 rp.moving_arg = true;
226                 TexString caption = getCaption(rp);
227                 os << breakln << "\\begin{lstlisting}";
228                 if (param_string.empty() && caption.str.empty())
229                         os << "\n";
230                 else {
231                         if (!runparams.nice)
232                                 os << safebreakln;
233                         os << "[";
234                         if (!caption.str.empty()) {
235                                 os << "caption={" << move(caption) << '}';
236                                 if (!param_string.empty())
237                                         os << ',';
238                         }
239                         os << from_utf8(param_string) << "]\n";
240                 }
241                 os << code << breakln << "\\end{lstlisting}\n";
242         }
243
244         if (encoding_switched){
245                 // Switch back
246                 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
247                 runparams.encoding = save_enc;
248         }
249
250         if (!uncodable.empty() && !runparams.silent) {
251                 // issue a warning about omitted characters
252                 // FIXME: should be passed to the error dialog
253                 if (!multibyte_possible && !runparams.encoding->hasFixedWidth())
254                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
255                                 bformat(_("The following characters in one of the program listings are\n"
256                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
257                                           "This is due to a restriction of the listings package, which does\n"
258                                           "not support your encoding '%2$s'.\n"
259                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
260                                           "might help."),
261                                 uncodable, _(runparams.encoding->guiName())));
262                 else
263                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
264                                 bformat(_("The following characters in one of the program listings are\n"
265                                           "not representable in the current encoding and have been omitted:\n%1$s."),
266                                 uncodable));
267         }
268 }
269
270
271 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
272 {
273         odocstringstream ods;
274         XHTMLStream out(ods);
275
276         bool const isInline = params().isInline();
277         if (isInline)
278                 out << html::CompTag("br");
279         else {
280                 out << html::StartTag("div", "class='float-listings'");
281                 docstring caption = getCaptionHTML(rp);
282                 if (!caption.empty())
283                         out << html::StartTag("div", "class='listings-caption'")
284                             << XHTMLStream::ESCAPE_NONE
285                             << caption << html::EndTag("div");
286         }
287
288         InsetLayout const & il = getLayout();
289         string const & tag = il.htmltag();
290         string attr = "class ='listings";
291         string const lang = params().getParamValue("language");
292         if (!lang.empty())
293                 attr += " " + lang;
294         attr += "'";
295         out << html::StartTag(tag, attr);
296         OutputParams newrp = rp;
297         newrp.html_disable_captions = true;
298         // We don't want to convert dashes here. That's the only conversion we
299         // do for XHTML, so this is safe.
300         newrp.pass_thru = true;
301         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
302         out << html::EndTag(tag);
303
304         if (isInline) {
305                 out << html::CompTag("br");
306                 // escaping will already have been done
307                 os << XHTMLStream::ESCAPE_NONE << ods.str();
308         } else {
309                 out << html::EndTag("div");
310                 // In this case, this needs to be deferred, but we'll put it
311                 // before anything the text itself deferred.
312                 def = ods.str() + '\n' + def;
313         }
314         return def;
315 }
316
317
318 string InsetListings::contextMenuName() const
319 {
320         return "context-listings";
321 }
322
323
324 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
325 {
326         switch (cmd.action()) {
327
328         case LFUN_INSET_MODIFY: {
329                 cur.recordUndoInset(this);
330                 InsetListings::string2params(to_utf8(cmd.argument()), params());
331                 break;
332         }
333
334         case LFUN_INSET_DIALOG_UPDATE:
335                 cur.bv().updateDialog("listings", params2string(params()));
336                 break;
337
338         default:
339                 InsetCaptionable::doDispatch(cur, cmd);
340                 break;
341         }
342 }
343
344
345 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
346         FuncStatus & status) const
347 {
348         switch (cmd.action()) {
349                 case LFUN_INSET_MODIFY:
350                 case LFUN_INSET_DIALOG_UPDATE:
351                         status.setEnabled(true);
352                         return true;
353                 case LFUN_CAPTION_INSERT: {
354                         // the inset outputs at most one caption
355                         if (params().isInline() || getCaptionInset()) {
356                                 status.setEnabled(false);
357                                 return true;
358                         }
359                 }
360                 default:
361                         return InsetCaptionable::getStatus(cur, cmd, status);
362         }
363 }
364
365
366 docstring const InsetListings::buttonLabel(BufferView const & bv) const
367 {
368         // FIXME UNICODE
369         if (decoration() == InsetLayout::CLASSIC)
370                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
371         else
372                 return getNewLabel(_("Listing"));
373 }
374
375
376 void InsetListings::validate(LaTeXFeatures & features) const
377 {
378         features.require("listings");
379         features.useInsetLayout(getLayout());
380         string param_string = params().params();
381         if (param_string.find("\\color") != string::npos)
382                 features.require("color");
383         InsetCaptionable::validate(features);
384 }
385
386
387 bool InsetListings::showInsetDialog(BufferView * bv) const
388 {
389         bv->showDialog("listings", params2string(params()),
390                 const_cast<InsetListings *>(this));
391         return true;
392 }
393
394
395 TexString InsetListings::getCaption(OutputParams const & runparams) const
396 {
397         InsetCaption const * ins = getCaptionInset();
398         if (ins == 0)
399                 return TexString();
400
401         otexstringstream os;
402         ins->getArgs(os, runparams);
403         ins->getArgument(os, runparams);
404
405         // TODO: The code below should be moved to support, and then the test
406         //       in ../tests should be moved there as well.
407
408         // the caption may contain \label{} but the listings
409         // package prefer caption={}, label={}
410         TexString cap = os.release();
411         if (!contains(cap.str, from_ascii("\\label{")))
412                 return cap;
413         // convert from
414         //     blah1\label{blah2} blah3
415         // to
416         //     blah1 blah3},label={blah2
417         // to form options
418         //     caption={blah1 blah3},label={blah2}
419         //
420         // NOTE that } is not allowed in blah2.
421         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
422         string const new_cap("$1$3},label={$2");
423         // TexString validity: the substitution preserves the number of newlines.
424         // Moreover we assume that $2 does not contain newlines, so that the texrow
425         // information remains accurate.
426         cap.str = from_utf8(regex_replace(to_utf8(cap.str), reg, new_cap));
427         return cap;
428 }
429
430
431 void InsetListings::string2params(string const & in,
432                                    InsetListingsParams & params)
433 {
434         params = InsetListingsParams();
435         if (in.empty())
436                 return;
437         istringstream data(in);
438         Lexer lex;
439         lex.setStream(data);
440         // discard "listings", which is only used to determine inset
441         lex.next();
442         params.read(lex);
443 }
444
445
446 string InsetListings::params2string(InsetListingsParams const & params)
447 {
448         ostringstream data;
449         data << "listings" << ' ';
450         params.write(data);
451         return data.str();
452 }
453
454
455 } // namespace lyx