]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Fix export of xfig external insets (bug #9244).
[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
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38 #include "support/lassert.h"
39
40 #include "frontends/alert.h"
41 #include "frontends/Application.h"
42
43 #include "support/regex.h"
44
45 #include <sstream>
46
47 using namespace std;
48 using namespace lyx::support;
49
50 namespace lyx {
51
52
53 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
54         : InsetCollapsable(buf)
55 {
56         status_ = par.status();
57 }
58
59
60 InsetListings::~InsetListings()
61 {
62         hideDialogs("listings", this);
63 }
64
65
66 Inset::DisplayType InsetListings::display() const
67 {
68         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
69 }
70
71
72 void InsetListings::updateBuffer(ParIterator const & it, UpdateType utype)
73 {
74         Counters & cnts =
75                 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::updateBuffer(it, utype);
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 void InsetListings::latex(otexstream & 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         bool const isInline = params().isInline();
132         // get the paragraphs. We can not output them directly to given odocstream
133         // because we can not yet determine the delimiter character of \lstinline
134         docstring code;
135         docstring uncodable;
136         ParagraphList::const_iterator par = paragraphs().begin();
137         ParagraphList::const_iterator end = paragraphs().end();
138
139         bool encoding_switched = false;
140         Encoding const * const save_enc = runparams.encoding;
141
142         if (!runparams.isFullUnicode()
143             && !runparams.encoding->hasFixedWidth()) {
144                 // We need to switch to a singlebyte encoding, since the
145                 // listings package cannot deal with multi-byte-encoded
146                 // glyphs (not needed with full-unicode aware backends
147                 // such as XeTeX).
148                 Language const * const outer_language =
149                         (runparams.local_font != 0) ?
150                                 runparams.local_font->language()
151                                 : buffer().params().language;
152                 // We try if there's a singlebyte encoding for the current
153                 // language; if not, fall back to latin1.
154                 Encoding const * const lstenc =
155                         (outer_language->encoding()->hasFixedWidth()) ?
156                                 outer_language->encoding() 
157                                 : encodings.fromLyXName("iso8859-1");
158                 switchEncoding(os.os(), buffer().params(), 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->encodable(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         }
201         if (isInline) {
202                 static const docstring delimiters =
203                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
204
205                 size_t pos = delimiters.find_first_not_of(code);
206
207                 // This code piece contains all possible special character? !!!
208                 // Replace ! with a warning message and use ! as delimiter.
209                 if (pos == string::npos) {
210                         docstring delim_error = "<" + _("LyX Warning: ")
211                                 + _("no more lstline delimiters available") + ">";
212                         code = subst(code, from_ascii("!"), delim_error);
213                         pos = 0;
214                         if (!runparams.dryrun && !runparams.silent) {
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                 docstring const delim(1, delimiters[pos]);
225                 os << "\\lstinline";
226                 if (!param_string.empty())
227                         os << "[" << from_utf8(param_string) << "]";
228                 else if (pos >= delimiters.find('Q'))
229                         // We need to terminate the command before the delimiter
230                         os << " ";
231                 os << delim << code << delim;
232         } else {
233                 OutputParams rp = runparams;
234                 rp.moving_arg = true;
235                 docstring const caption = getCaption(rp);
236                 if (param_string.empty() && caption.empty())
237                         os << breakln << "\\begin{lstlisting}\n";
238                 else {
239                         os << breakln << "\\begin{lstlisting}[";
240                         if (!caption.empty()) {
241                                 os << "caption={" << caption << '}';
242                                 if (!param_string.empty())
243                                         os << ',';
244                         }
245                         os << from_utf8(param_string) << "]\n";
246                 }
247                 os << code << breakln << "\\end{lstlisting}\n";
248         }
249
250         if (encoding_switched){
251                 // Switch back
252                 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
253                 runparams.encoding = save_enc;
254         }
255
256         if (!uncodable.empty() && !runparams.silent) {
257                 // issue a warning about omitted characters
258                 // FIXME: should be passed to the error dialog
259                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
260                         bformat(_("The following characters in one of the program listings are\n"
261                                   "not representable in the current encoding and have been omitted:\n%1$s."),
262                         uncodable));
263         }
264 }
265
266
267 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
268 {
269         odocstringstream ods;
270         XHTMLStream out(ods);
271
272         bool const isInline = params().isInline();
273         if (isInline) 
274                 out << html::CompTag("br");
275         else {
276                 out << html::StartTag("div", "class='float float-listings'");
277                 docstring caption = getCaptionHTML(rp);
278                 if (!caption.empty())
279                         out << html::StartTag("div", "class='float-caption'") 
280                             << XHTMLStream::ESCAPE_NONE
281                             << caption << html::EndTag("div");
282         }
283
284         InsetLayout const & il = getLayout();
285         string const tag = il.htmltag();
286         string attr = "class ='listings";
287         string const lang = params().getParamValue("language");
288         if (!lang.empty())
289                 attr += " " + lang;
290         attr += "'";
291         out << html::StartTag(tag, attr);
292         OutputParams newrp = rp;
293         newrp.html_disable_captions = true;
294         // We don't want to convert dashes here. That's the only conversion we
295         // do for XHTML, so this is safe.
296         newrp.pass_thru = true;
297         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
298         out << html::EndTag(tag);
299
300         if (isInline) {
301                 out << html::CompTag("br");
302                 // escaping will already have been done
303                 os << XHTMLStream::ESCAPE_NONE << ods.str();
304         } else {
305                 out << html::EndTag("div");
306                 // In this case, this needs to be deferred, but we'll put it
307                 // before anything the text itself deferred.
308                 def = ods.str() + '\n' + def;
309         }
310         return def;
311 }
312
313
314 string InsetListings::contextMenuName() const
315 {
316         return "context-listings";
317 }
318
319
320 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
321 {
322         switch (cmd.action()) {
323
324         case LFUN_INSET_MODIFY: {
325                 cur.recordUndoInset(ATOMIC_UNDO, this);
326                 InsetListings::string2params(to_utf8(cmd.argument()), params());
327                 break;
328         }
329
330         case LFUN_INSET_DIALOG_UPDATE:
331                 cur.bv().updateDialog("listings", params2string(params()));
332                 break;
333
334         default:
335                 InsetCollapsable::doDispatch(cur, cmd);
336                 break;
337         }
338 }
339
340
341 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
342         FuncStatus & status) const
343 {
344         switch (cmd.action()) {
345                 case LFUN_INSET_MODIFY:
346                 case LFUN_INSET_DIALOG_UPDATE:
347                         status.setEnabled(true);
348                         return true;
349                 case LFUN_CAPTION_INSERT: {
350                         if (params().isInline()) {
351                                 status.setEnabled(false);
352                                 return true;
353                         }
354                 }
355                 default:
356                         return InsetCollapsable::getStatus(cur, cmd, status);
357         }
358 }
359
360
361 docstring const InsetListings::buttonLabel(BufferView const & bv) const
362 {
363         // FIXME UNICODE
364         if (decoration() == InsetLayout::CLASSIC)
365                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
366         else
367                 return getNewLabel(_("Listing"));
368 }
369
370
371 void InsetListings::validate(LaTeXFeatures & features) const
372 {
373         features.require("listings");
374         string param_string = params().params();
375         if (param_string.find("\\color") != string::npos)
376                 features.require("color");
377         InsetCollapsable::validate(features);
378 }
379
380
381 bool InsetListings::showInsetDialog(BufferView * bv) const
382 {
383         bv->showDialog("listings", params2string(params()),
384                 const_cast<InsetListings *>(this));
385         return true;
386 }
387
388
389 docstring InsetListings::getCaption(OutputParams const & runparams) const
390 {
391         if (paragraphs().empty())
392                 return docstring();
393
394         InsetCaption const * ins = getCaptionInset();
395         if (ins == 0)
396                 return docstring();
397
398         TexRow texrow;
399         odocstringstream ods;
400         otexstream os(ods, texrow);
401         ins->getArgs(os, runparams);
402         ins->getArgument(os, runparams);
403         // the caption may contain \label{} but the listings
404         // package prefer caption={}, label={}
405         docstring cap = ods.str();
406         if (!contains(to_utf8(cap), "\\label{"))
407                 return cap;
408         // convert from
409         //     blah1\label{blah2} blah3
410         // to
411         //     blah1 blah3},label={blah2
412         // to form options
413         //     caption={blah1 blah3},label={blah2}
414         //
415         // NOTE that } is not allowed in blah2.
416         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
417         string const new_cap("\\1\\3},label={\\2");
418         return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
419 }
420
421
422 void InsetListings::string2params(string const & in,
423                                    InsetListingsParams & params)
424 {
425         params = InsetListingsParams();
426         if (in.empty())
427                 return;
428         istringstream data(in);
429         Lexer lex;
430         lex.setStream(data);
431         // discard "listings", which is only used to determine inset
432         lex.next();
433         params.read(lex);
434 }
435
436
437 string InsetListings::params2string(InsetListingsParams const & params)
438 {
439         ostringstream data;
440         data << "listings" << ' ';
441         params.write(data);
442         return data.str();
443 }
444
445
446 } // namespace lyx