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