]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
bbd2b53aebd794348810f03dda2a7781fd590e3f
[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 "Lexer.h"
28 #include "output_latex.h"
29 #include "output_xhtml.h"
30 #include "TextClass.h"
31
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36 #include "support/lassert.h"
37
38 #include "frontends/alert.h"
39 #include "frontends/Application.h"
40
41 #include <boost/regex.hpp>
42
43 #include <sstream>
44
45 using namespace std;
46 using namespace lyx::support;
47
48 namespace lyx {
49
50 using boost::regex;
51
52 char const lstinline_delimiters[] =
53         "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
54
55 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
56         : InsetCollapsable(buf)
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::updateBuffer(ParIterator const & it, UpdateType utype)
75 {
76         Counters & cnts =
77                 buffer().masterBuffer()->params().documentClass().counters();
78         string const saveflt = cnts.current_float();
79
80         // Tell to captions what the current float is
81         cnts.current_float("listing");
82
83         InsetCollapsable::updateBuffer(it, utype);
84
85         //reset afterwards
86         cnts.current_float(saveflt);
87 }
88
89
90 void InsetListings::write(ostream & os) const
91 {
92         os << "listings" << "\n";
93         InsetListingsParams const & par = params();
94         // parameter string is encoded to be a valid lyx token.
95         string opt = par.encodedString();
96         if (!opt.empty())
97                 os << "lstparams \"" << opt << "\"\n";
98         if (par.isInline())
99                 os << "inline true\n";
100         else
101                 os << "inline false\n";
102         InsetCollapsable::write(os);
103 }
104
105
106 void InsetListings::read(Lexer & lex)
107 {
108         while (lex.isOK()) {
109                 lex.next();
110                 string token = lex.getString();
111                 if (token == "lstparams") {
112                         lex.next();
113                         string const value = lex.getString();
114                         params().fromEncodedString(value);
115                 } else if (token == "inline") {
116                         lex.next();
117                         params().setInline(lex.getBool());
118                 } else {
119                         // no special option, push back 'status' etc
120                         lex.pushToken(token);
121                         break;
122                 }
123         }
124         InsetCollapsable::read(lex);
125 }
126
127
128 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
129 {
130         string param_string = params().params();
131         // NOTE: I use {} to quote text, which is an experimental feature
132         // of the listings package (see page 25 of the manual)
133         int lines = 0;
134         bool const isInline = params().isInline();
135         // get the paragraphs. We can not output them directly to given odocstream
136         // because we can not yet determine the delimiter character of \lstinline
137         docstring code;
138         docstring uncodable;
139         ParagraphList::const_iterator par = paragraphs().begin();
140         ParagraphList::const_iterator end = paragraphs().end();
141
142         bool encoding_switched = false;
143         Encoding const * const save_enc = runparams.encoding;
144
145         if (runparams.flavor != OutputParams::XETEX
146             && !runparams.encoding->hasFixedWidth()) {
147                 // We need to switch to a singlebyte encoding, since the
148                 // listings package cannot deal with multi-byte-encoded
149                 // glyphs (not needed with XeTeX).
150                 Language const * const outer_language =
151                         (runparams.local_font != 0) ?
152                                 runparams.local_font->language()
153                                 : buffer().params().language;
154                 // We try if there's a singlebyte encoding for the current
155                 // language; if not, fall back to latin1.
156                 Encoding const * const lstenc =
157                         (outer_language->encoding()->hasFixedWidth()) ?
158                                 outer_language->encoding() 
159                                 : encodings.fromLyXName("iso8859-1");
160                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
161                                 runparams, *lstenc, true);
162                 runparams.encoding = lstenc;
163                 encoding_switched = true;
164         }
165
166         while (par != end) {
167                 pos_type siz = par->size();
168                 bool captionline = false;
169                 for (pos_type i = 0; i < siz; ++i) {
170                         if (i == 0 && par->isInset(i) && i + 1 == siz)
171                                 captionline = true;
172                         // ignore all struck out text and (caption) insets
173                         if (par->isDeleted(i) || par->isInset(i))
174                                 continue;
175                         char_type c = par->getChar(i);
176                         // we can only output characters covered by the current
177                         // encoding!
178                         try {
179                                 if (runparams.encoding->latexChar(c) == docstring(1, c))
180                                         code += c;
181                                 else if (runparams.dryrun) {
182                                         code += "<" + _("LyX Warning: ")
183                                            + _("uncodable character") + " '";
184                                         code += docstring(1, c);
185                                         code += "'>";
186                                 } else
187                                         uncodable += c;
188                         } catch (EncodingException & /* e */) {
189                                 if (runparams.dryrun) {
190                                         code += "<" + _("LyX Warning: ")
191                                            + _("uncodable character") + " '";
192                                         code += docstring(1, c);
193                                         code += "'>";
194                                 } else
195                                         uncodable += c;
196                         }
197                 }
198                 ++par;
199                 // for the inline case, if there are multiple paragraphs
200                 // they are simply joined. Otherwise, expect latex errors.
201                 if (par != end && !isInline && !captionline) {
202                         code += "\n";
203                         ++lines;
204                 }
205         }
206         if (isInline) {
207                 char const * delimiter = lstinline_delimiters;
208                 for (; delimiter != '\0'; ++delimiter)
209                         if (!contains(code, *delimiter))
210                                 break;
211                 // This code piece contains all possible special character? !!!
212                 // Replace ! with a warning message and use ! as delimiter.
213                 if (*delimiter == '\0') {
214                         docstring delim_error = "<" + _("LyX Warning: ")
215                                 + _("no more lstline delimiters available") + ">";
216                         code = subst(code, from_ascii("!"), delim_error);
217                         delimiter = lstinline_delimiters;
218                         if (!runparams.dryrun) {
219                                 // FIXME: warning should be passed to the error dialog
220                                 frontend::Alert::warning(_("Running out of delimiters"),
221                                 _("For inline program listings, one character must be reserved\n"
222                                   "as a delimiter. One of the listings, however, uses all available\n"
223                                   "characters, so none is left for delimiting purposes.\n"
224                                   "For the time being, I have replaced '!' by a warning, but you\n"
225                                   "must investigate!"));
226                         }
227                 }
228                 if (param_string.empty())
229                         os << "\\lstinline" << *delimiter;
230                 else
231                         os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
232                 os << code
233                    << *delimiter;
234         } else {
235                 OutputParams rp = runparams;
236                 rp.moving_arg = true;
237                 docstring const caption = getCaption(rp);
238                 if (param_string.empty() && caption.empty())
239                         os << "\n\\begin{lstlisting}\n";
240                 else {
241                         os << "\n\\begin{lstlisting}[";
242                         if (!caption.empty()) {
243                                 os << "caption={" << caption << '}';
244                                 if (!param_string.empty())
245                                         os << ',';
246                         }
247                         os << from_utf8(param_string) << "]\n";
248                 }
249                 lines += 2;
250                 os << code << "\n\\end{lstlisting}\n";
251                 lines += 2;
252         }
253
254         if (encoding_switched){
255                 // Switch back
256                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
257                                 runparams, *save_enc, true);
258                 runparams.encoding = save_enc;
259         }
260
261         if (!uncodable.empty()) {
262                 // issue a warning about omitted characters
263                 // FIXME: should be passed to the error dialog
264                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
265                         bformat(_("The following characters in one of the program listings are\n"
266                                   "not representable in the current encoding and have been omitted:\n%1$s."),
267                         uncodable));
268         }
269
270         return lines;
271 }
272
273
274 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
275 {
276         odocstringstream ods;
277         XHTMLStream out(ods);
278
279         bool const isInline = params().isInline();
280         if (isInline) 
281                 out << html::CompTag("br");
282         else {
283                 out << html::StartTag("div", "class='float float-listings'");
284                 docstring caption = getCaptionHTML(rp);
285                 if (!caption.empty())
286                         out << html::StartTag("div", "class='float-caption'") 
287                             << caption << html::EndTag("div");
288         }
289
290         out << html::StartTag("pre");
291         OutputParams newrp = rp;
292         newrp.html_disable_captions = true;
293         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
294         out << html::EndTag("pre");
295
296         if (isInline) {
297                 out << html::CompTag("br");
298                 // escaping will already have been done
299                 os << XHTMLStream::NextRaw() << ods.str();
300         } else {
301                 out << html::EndTag("div");
302                 // In this case, this needs to be deferred, but we'll put it
303                 // before anything the text itself deferred.
304                 def = ods.str() + '\n' + def;
305         }
306         return def;
307 }
308
309
310 docstring InsetListings::contextMenu(BufferView const &, int, int) const
311 {
312         return from_ascii("context-listings");
313 }
314
315
316 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
317 {
318         switch (cmd.action()) {
319
320         case LFUN_INSET_MODIFY: {
321                 InsetListings::string2params(to_utf8(cmd.argument()), params());
322                 break;
323         }
324
325         case LFUN_INSET_DIALOG_UPDATE:
326                 cur.bv().updateDialog("listings", params2string(params()));
327                 break;
328
329         default:
330                 InsetCollapsable::doDispatch(cur, cmd);
331                 break;
332         }
333 }
334
335
336 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
337         FuncStatus & status) const
338 {
339         switch (cmd.action()) {
340                 case LFUN_INSET_MODIFY:
341                 case LFUN_INSET_DIALOG_UPDATE:
342                         status.setEnabled(true);
343                         return true;
344                 case LFUN_CAPTION_INSERT:
345                         status.setEnabled(!params().isInline());
346                         return true;
347                 default:
348                         return InsetCollapsable::getStatus(cur, cmd, status);
349         }
350 }
351
352
353 docstring const InsetListings::buttonLabel(BufferView const & bv) const
354 {
355         // FIXME UNICODE
356         if (decoration() == InsetLayout::CLASSIC)
357                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
358         else
359                 return getNewLabel(_("Listing"));
360 }
361
362
363 void InsetListings::validate(LaTeXFeatures & features) const
364 {
365         features.require("listings");
366         string param_string = params().params();
367         if (param_string.find("\\color") != string::npos)
368                 features.require("color");
369         InsetCollapsable::validate(features);
370 }
371
372
373 bool InsetListings::showInsetDialog(BufferView * bv) const
374 {
375         bv->showDialog("listings", params2string(params()),
376                 const_cast<InsetListings *>(this));
377         return true;
378 }
379
380
381 docstring InsetListings::getCaption(OutputParams const & runparams) const
382 {
383         if (paragraphs().empty())
384                 return docstring();
385
386         InsetCaption const * ins = getCaptionInset();
387         if (ins == 0)
388                 return docstring();
389
390         odocstringstream ods;
391         ins->getOptArg(ods, runparams);
392         ins->getArgument(ods, runparams);
393         // the caption may contain \label{} but the listings
394         // package prefer caption={}, label={}
395         docstring cap = ods.str();
396         if (!contains(to_utf8(cap), "\\label{"))
397                 return cap;
398         // convert from
399         //     blah1\label{blah2} blah3
400         // to
401         //     blah1 blah3},label={blah2
402         // to form options
403         //     caption={blah1 blah3},label={blah2}
404         //
405         // NOTE that } is not allowed in blah2.
406         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
407         string const new_cap("\\1\\3},label={\\2");
408         return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
409 }
410
411
412 void InsetListings::string2params(string const & in,
413                                    InsetListingsParams & params)
414 {
415         params = InsetListingsParams();
416         if (in.empty())
417                 return;
418         istringstream data(in);
419         Lexer lex;
420         lex.setStream(data);
421         // discard "listings", which is only used to determine inset
422         lex.next();
423         params.read(lex);
424 }
425
426
427 string InsetListings::params2string(InsetListingsParams const & params)
428 {
429         ostringstream data;
430         data << "listings" << ' ';
431         params.write(data);
432         return data.str();
433 }
434
435
436 } // namespace lyx