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