]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
fix MSVC warning.
[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 "InsetList.h"
27 #include "Language.h"
28 #include "MetricsInfo.h"
29 #include "output_latex.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
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, par.status())
56 {}
57
58
59 InsetListings::~InsetListings()
60 {
61         hideDialogs("listings", this);
62 }
63
64
65 Inset::DisplayType InsetListings::display() const
66 {
67         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
68 }
69
70
71 void InsetListings::updateLabels(ParIterator const & it)
72 {
73         Counters & cnts = buffer().params().documentClass().counters();
74         string const saveflt = cnts.current_float();
75
76         // Tell to captions what the current float is
77         cnts.current_float("listing");
78
79         InsetCollapsable::updateLabels(it);
80
81         //reset afterwards
82         cnts.current_float(saveflt);
83 }
84
85
86 void InsetListings::write(ostream & os) const
87 {
88         os << "listings" << "\n";
89         InsetListingsParams const & par = params();
90         // parameter string is encoded to be a valid lyx token.
91         string opt = par.encodedString();
92         if (!opt.empty())
93                 os << "lstparams \"" << opt << "\"\n";
94         if (par.isInline())
95                 os << "inline true\n";
96         else
97                 os << "inline false\n";
98         InsetCollapsable::write(os);
99 }
100
101
102 void InsetListings::read(Lexer & lex)
103 {
104         while (lex.isOK()) {
105                 lex.next();
106                 string token = lex.getString();
107                 if (token == "lstparams") {
108                         lex.next();
109                         string const value = lex.getString();
110                         params().fromEncodedString(value);
111                 } else if (token == "inline") {
112                         lex.next();
113                         params().setInline(lex.getBool());
114                 } else {
115                         // no special option, push back 'status' etc
116                         lex.pushToken(token);
117                         break;
118                 }
119         }
120         InsetCollapsable::read(lex);
121 }
122
123
124 docstring InsetListings::editMessage() const
125 {
126         return _("Opened Listing Inset");
127 }
128
129
130 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
131 {
132         string param_string = params().params();
133         // NOTE: I use {} to quote text, which is an experimental feature
134         // of the listings package (see page 25 of the manual)
135         int lines = 0;
136         bool isInline = params().isInline();
137         // get the paragraphs. We can not output them directly to given odocstream
138         // because we can not yet determine the delimiter character of \lstinline
139         docstring code;
140         docstring uncodable;
141         ParagraphList::const_iterator par = paragraphs().begin();
142         ParagraphList::const_iterator end = paragraphs().end();
143
144         bool encoding_switched = false;
145         Encoding const * const save_enc = runparams.encoding;
146
147         if (!runparams.encoding->hasFixedWidth()) {
148                 // We need to switch to a singlebyte encoding, since the listings
149                 // package cannot deal with multiple-byte-encoded glyphs
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_ascii(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                 runparams.encoding = rp.encoding;
239                 if (param_string.empty() && caption.empty())
240                         os << "\n\\begin{lstlisting}\n";
241                 else {
242                         os << "\n\\begin{lstlisting}[";
243                         if (!caption.empty()) {
244                                 os << "caption={" << caption << '}';
245                                 if (!param_string.empty())
246                                         os << ',';
247                         }
248                         os << from_utf8(param_string) << "]\n";
249                 }
250                 lines += 2;
251                 os << code << "\n\\end{lstlisting}\n";
252                 lines += 2;
253         }
254
255         if (encoding_switched){
256                 // Switch back
257                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
258                                 runparams, *save_enc, true);
259                 runparams.encoding = save_enc;
260         }
261
262         if (!uncodable.empty()) {
263                 // issue a warning about omitted characters
264                 // FIXME: should be passed to the error dialog
265                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
266                         bformat(_("The following characters in one of the program listings are\n"
267                                   "not representable in the current encoding and have been omitted:\n%1$s."),
268                         uncodable));
269         }
270
271         return lines;
272 }
273
274
275 docstring InsetListings::contextMenu(BufferView const &, int, int) const
276 {
277         return from_ascii("context-listings");
278 }
279
280
281 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
282 {
283         switch (cmd.action) {
284
285         case LFUN_INSET_MODIFY: {
286                 InsetListings::string2params(to_utf8(cmd.argument()), params());
287                 break;
288         }
289         case LFUN_INSET_DIALOG_UPDATE:
290                 cur.bv().updateDialog("listings", params2string(params()));
291                 break;
292         default:
293                 InsetCollapsable::doDispatch(cur, cmd);
294                 break;
295         }
296 }
297
298
299 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
300         FuncStatus & status) const
301 {
302         switch (cmd.action) {
303                 case LFUN_INSET_MODIFY:
304                 case LFUN_INSET_DIALOG_UPDATE:
305                         status.setEnabled(true);
306                         return true;
307                 case LFUN_CAPTION_INSERT:
308                         status.setEnabled(!params().isInline());
309                         return true;
310                 default:
311                         return InsetCollapsable::getStatus(cur, cmd, status);
312         }
313 }
314
315
316 void InsetListings::setButtonLabel()
317 {
318         // FIXME UNICODE
319         if (decoration() == InsetLayout::Classic)
320                 setLabel(isOpen() ?  _("Listing") : getNewLabel(_("Listing")));
321         else
322                 setLabel(getNewLabel(_("Listing")));
323 }
324
325
326 void InsetListings::validate(LaTeXFeatures & features) const
327 {
328         features.require("listings");
329         InsetCollapsable::validate(features);
330 }
331
332
333 bool InsetListings::showInsetDialog(BufferView * bv) const
334 {
335         bv->showDialog("listings", params2string(params()),
336                 const_cast<InsetListings *>(this));
337         return true;
338 }
339
340
341 docstring InsetListings::getCaption(OutputParams const & runparams) const
342 {
343         if (paragraphs().empty())
344                 return docstring();
345
346         ParagraphList::const_iterator pit = paragraphs().begin();
347         for (; pit != paragraphs().end(); ++pit) {
348                 InsetList::const_iterator it = pit->insetList().begin();
349                 for (; it != pit->insetList().end(); ++it) {
350                         Inset & inset = *it->inset;
351                         if (inset.lyxCode() == CAPTION_CODE) {
352                                 odocstringstream ods;
353                                 InsetCaption * ins =
354                                         static_cast<InsetCaption *>(it->inset);
355                                 ins->getOptArg(ods, runparams);
356                                 ins->getArgument(ods, runparams);
357                                 // the caption may contain \label{} but the listings
358                                 // package prefer caption={}, label={}
359                                 docstring cap = ods.str();
360                                 if (!contains(to_utf8(cap), "\\label{"))
361                                         return cap;
362                                 // convert from
363                                 //     blah1\label{blah2} blah3
364                                 // to
365                                 //     blah1 blah3},label={blah2
366                                 // to form options
367                                 //     caption={blah1 blah3},label={blah2}
368                                 //
369                                 // NOTE that } is not allowed in blah2.
370                                 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
371                                 string const new_cap("\\1\\3},label={\\2");
372                                 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
373                         }
374                 }
375         }
376         return docstring();
377 }
378
379
380 void InsetListings::string2params(string const & in,
381                                    InsetListingsParams & params)
382 {
383         params = InsetListingsParams();
384         if (in.empty())
385                 return;
386         istringstream data(in);
387         Lexer lex;
388         lex.setStream(data);
389         // discard "listings", which is only used to determine inset
390         lex.next();
391         params.read(lex);
392 }
393
394
395 string InsetListings::params2string(InsetListingsParams const & params)
396 {
397         ostringstream data;
398         data << "listings" << ' ';
399         params.write(data);
400         return data.str();
401 }
402
403
404 } // namespace lyx