]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
693e205ec1ec20fb9ab72e7dfea9f1e55fc2f0e0
[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 #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 const & 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)
75 {
76         Counters & cnts = buffer().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);
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 docstring InsetListings::editMessage() const
128 {
129         return _("Opened Listing Inset");
130 }
131
132
133 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
134 {
135         string param_string = params().params();
136         // NOTE: I use {} to quote text, which is an experimental feature
137         // of the listings package (see page 25 of the manual)
138         int lines = 0;
139         bool isInline = params().isInline();
140         // get the paragraphs. We can not output them directly to given odocstream
141         // because we can not yet determine the delimiter character of \lstinline
142         docstring code;
143         docstring uncodable;
144         ParagraphList::const_iterator par = paragraphs().begin();
145         ParagraphList::const_iterator end = paragraphs().end();
146
147         bool encoding_switched = false;
148         Encoding const * const save_enc = runparams.encoding;
149
150         if (!runparams.encoding->hasFixedWidth()) {
151                 // We need to switch to a singlebyte encoding, since the listings
152                 // package cannot deal with multiple-byte-encoded glyphs
153                 Language const * const outer_language =
154                         (runparams.local_font != 0) ?
155                                 runparams.local_font->language()
156                                 : buffer().params().language;
157                 // We try if there's a singlebyte encoding for the current
158                 // language; if not, fall back to latin1.
159                 Encoding const * const lstenc =
160                         (outer_language->encoding()->hasFixedWidth()) ?
161                                 outer_language->encoding() 
162                                 : encodings.fromLyXName("iso8859-1");
163                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
164                                 runparams, *lstenc, true);
165                 runparams.encoding = lstenc;
166                 encoding_switched = true;
167         }
168
169         while (par != end) {
170                 pos_type siz = par->size();
171                 bool captionline = false;
172                 for (pos_type i = 0; i < siz; ++i) {
173                         if (i == 0 && par->isInset(i) && i + 1 == siz)
174                                 captionline = true;
175                         // ignore all struck out text and (caption) insets
176                         if (par->isDeleted(i) || par->isInset(i))
177                                 continue;
178                         char_type c = par->getChar(i);
179                         // we can only output characters covered by the current
180                         // encoding!
181                         try {
182                                 if (runparams.encoding->latexChar(c) == docstring(1, c))
183                                         code += c;
184                                 else if (runparams.dryrun) {
185                                         code += "<" + _("LyX Warning: ")
186                                            + _("uncodable character") + " '";
187                                         code += docstring(1, c);
188                                         code += "'>";
189                                 } else
190                                         uncodable += c;
191                         } catch (EncodingException & /* e */) {
192                                 if (runparams.dryrun) {
193                                         code += "<" + _("LyX Warning: ")
194                                            + _("uncodable character") + " '";
195                                         code += docstring(1, c);
196                                         code += "'>";
197                                 } else
198                                         uncodable += c;
199                         }
200                 }
201                 ++par;
202                 // for the inline case, if there are multiple paragraphs
203                 // they are simply joined. Otherwise, expect latex errors.
204                 if (par != end && !isInline && !captionline) {
205                         code += "\n";
206                         ++lines;
207                 }
208         }
209         if (isInline) {
210                 char const * delimiter = lstinline_delimiters;
211                 for (; delimiter != '\0'; ++delimiter)
212                         if (!contains(code, *delimiter))
213                                 break;
214                 // This code piece contains all possible special character? !!!
215                 // Replace ! with a warning message and use ! as delimiter.
216                 if (*delimiter == '\0') {
217                         docstring delim_error = "<" + _("LyX Warning: ")
218                                 + _("no more lstline delimiters available") + ">";
219                         code = subst(code, from_ascii("!"), delim_error);
220                         delimiter = lstinline_delimiters;
221                         if (!runparams.dryrun) {
222                                 // FIXME: warning should be passed to the error dialog
223                                 frontend::Alert::warning(_("Running out of delimiters"),
224                                 _("For inline program listings, one character must be reserved\n"
225                                   "as a delimiter. One of the listings, however, uses all available\n"
226                                   "characters, so none is left for delimiting purposes.\n"
227                                   "For the time being, I have replaced '!' by a warning, but you\n"
228                                   "must investigate!"));
229                         }
230                 }
231                 if (param_string.empty())
232                         os << "\\lstinline" << *delimiter;
233                 else
234                         os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
235                 os << code
236                    << *delimiter;
237         } else {
238                 OutputParams rp = runparams;
239                 rp.moving_arg = true;
240                 docstring const caption = getCaption(rp);
241                 runparams.encoding = rp.encoding;
242                 if (param_string.empty() && caption.empty())
243                         os << "\n\\begin{lstlisting}\n";
244                 else {
245                         os << "\n\\begin{lstlisting}[";
246                         if (!caption.empty()) {
247                                 os << "caption={" << caption << '}';
248                                 if (!param_string.empty())
249                                         os << ',';
250                         }
251                         os << from_utf8(param_string) << "]\n";
252                 }
253                 lines += 2;
254                 os << code << "\n\\end{lstlisting}\n";
255                 lines += 2;
256         }
257
258         if (encoding_switched){
259                 // Switch back
260                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
261                                 runparams, *save_enc, true);
262                 runparams.encoding = save_enc;
263         }
264
265         if (!uncodable.empty()) {
266                 // issue a warning about omitted characters
267                 // FIXME: should be passed to the error dialog
268                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
269                         bformat(_("The following characters in one of the program listings are\n"
270                                   "not representable in the current encoding and have been omitted:\n%1$s."),
271                         uncodable));
272         }
273
274         return lines;
275 }
276
277
278 docstring InsetListings::contextMenu(BufferView const &, int, int) const
279 {
280         return from_ascii("context-listings");
281 }
282
283
284 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
285 {
286         switch (cmd.action) {
287
288         case LFUN_INSET_MODIFY: {
289                 InsetListings::string2params(to_utf8(cmd.argument()), params());
290                 break;
291         }
292         case LFUN_INSET_DIALOG_UPDATE:
293                 cur.bv().updateDialog("listings", params2string(params()));
294                 break;
295         case LFUN_TAB_INSERT:
296                 if (cur.selection()) {
297                         // If there is a selection, a tab is inserted at the
298                         // beginning of each paragraph.
299                         cur.recordUndoSelection();
300                         pit_type const pit_end = cur.selEnd().pit();
301                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
302                                 paragraphs()[pit].insertChar(0, '\t', 
303                                         buffer().params().trackChanges);
304                                 // Update the selection pos to make sure the selection does not
305                                 // change as the inserted tab will increase the logical pos.
306                                 if (cur.anchor_.pit() == pit)
307                                         cur.anchor_.forwardPos();
308                                 if (cur.pit() == pit)
309                                         cur.forwardPos();
310                         }
311                         cur.finishUndo();
312                 } else {
313                         // Maybe we shouldn't allow tabs within a line, because they
314                         // are not (yet) aligned as one might do expect.
315                         cur.recordUndo();
316                         cur.insert(from_ascii("\t"));
317                         cur.finishUndo();
318                 }
319                 break;
320         case LFUN_TAB_DELETE:
321                 if (cur.selection()) {
322                         // If there is a selection, a tab (if present) is removed from
323                         // the beginning of each paragraph.
324                         cur.recordUndoSelection();
325                         pit_type const pit_end = cur.selEnd().pit();
326                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
327                                 Paragraph & par = paragraphs()[pit];
328                                 if (par.getChar(0) == '\t') {
329                                         if (cur.pit() == pit)
330                                                 cur.posBackward();
331                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
332                                                 cur.anchor_.backwardPos();
333
334                                         par.eraseChar(0, buffer().params().trackChanges);
335                                 } else 
336                                         // If no tab was present, try to remove up to four spaces.
337                                         for (int n_spaces = 0;
338                                                 par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
339                                                         if (cur.pit() == pit)
340                                                                 cur.posBackward();
341                                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
342                                                                 cur.anchor_.backwardPos();
343
344                                                         par.eraseChar(0, buffer().params().trackChanges);
345                                         }
346                         }
347                         cur.finishUndo();
348                 } else {
349                         // If there is no selection, try to remove a tab or some spaces 
350                         // before the position of the cursor.
351                         Paragraph & par = paragraphs()[cur.pit()];
352                         pos_type const pos = cur.pos();
353
354                         if (pos == 0)
355                                 break;
356
357                         char_type const c = par.getChar(pos - 1);
358                         cur.recordUndo();
359                         if (c == '\t') {
360                                 cur.posBackward();
361                                 par.eraseChar(cur.pos(), buffer().params().trackChanges);
362                         } else
363                                 for (int n_spaces = 0; cur.pos() > 0
364                                         && par.getChar(cur.pos() - 1) == ' ' && n_spaces < 4;
365                                         ++n_spaces) {
366                                                 cur.posBackward();
367                                                 par.eraseChar(cur.pos(), buffer().params().trackChanges);
368                                 }
369                                 cur.finishUndo();
370                 }
371                 break;
372         default:
373                 InsetCollapsable::doDispatch(cur, cmd);
374                 break;
375         }
376 }
377
378
379 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
380         FuncStatus & status) const
381 {
382         switch (cmd.action) {
383                 case LFUN_INSET_MODIFY:
384                 case LFUN_INSET_DIALOG_UPDATE:
385                         status.setEnabled(true);
386                         return true;
387                 case LFUN_CAPTION_INSERT:
388                         status.setEnabled(!params().isInline());
389                         return true;
390                         case LFUN_TAB_INSERT:
391                         case LFUN_TAB_DELETE:
392                                 status.setEnabled(true);
393                                 return true;
394                 default:
395                         return InsetCollapsable::getStatus(cur, cmd, status);
396         }
397 }
398
399
400 void InsetListings::setButtonLabel()
401 {
402         // FIXME UNICODE
403         if (decoration() == InsetLayout::CLASSIC)
404                 setLabel(isOpen() ?  _("Listing") : getNewLabel(_("Listing")));
405         else
406                 setLabel(getNewLabel(_("Listing")));
407 }
408
409
410 void InsetListings::validate(LaTeXFeatures & features) const
411 {
412         features.require("listings");
413         string param_string = params().params();
414         if (param_string.find("\\color") != string::npos)
415                 features.require("color");
416         InsetCollapsable::validate(features);
417 }
418
419
420 bool InsetListings::showInsetDialog(BufferView * bv) const
421 {
422         bv->showDialog("listings", params2string(params()),
423                 const_cast<InsetListings *>(this));
424         return true;
425 }
426
427
428 docstring InsetListings::getCaption(OutputParams const & runparams) const
429 {
430         if (paragraphs().empty())
431                 return docstring();
432
433         ParagraphList::const_iterator pit = paragraphs().begin();
434         for (; pit != paragraphs().end(); ++pit) {
435                 InsetList::const_iterator it = pit->insetList().begin();
436                 for (; it != pit->insetList().end(); ++it) {
437                         Inset & inset = *it->inset;
438                         if (inset.lyxCode() == CAPTION_CODE) {
439                                 odocstringstream ods;
440                                 InsetCaption * ins =
441                                         static_cast<InsetCaption *>(it->inset);
442                                 ins->getOptArg(ods, runparams);
443                                 ins->getArgument(ods, runparams);
444                                 // the caption may contain \label{} but the listings
445                                 // package prefer caption={}, label={}
446                                 docstring cap = ods.str();
447                                 if (!contains(to_utf8(cap), "\\label{"))
448                                         return cap;
449                                 // convert from
450                                 //     blah1\label{blah2} blah3
451                                 // to
452                                 //     blah1 blah3},label={blah2
453                                 // to form options
454                                 //     caption={blah1 blah3},label={blah2}
455                                 //
456                                 // NOTE that } is not allowed in blah2.
457                                 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
458                                 string const new_cap("\\1\\3},label={\\2");
459                                 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
460                         }
461                 }
462         }
463         return docstring();
464 }
465
466
467 void InsetListings::string2params(string const & in,
468                                    InsetListingsParams & params)
469 {
470         params = InsetListingsParams();
471         if (in.empty())
472                 return;
473         istringstream data(in);
474         Lexer lex;
475         lex.setStream(data);
476         // discard "listings", which is only used to determine inset
477         lex.next();
478         params.read(lex);
479 }
480
481
482 string InsetListings::params2string(InsetListingsParams const & params)
483 {
484         ostringstream data;
485         data << "listings" << ' ';
486         params.write(data);
487         return data.str();
488 }
489
490
491 } // namespace lyx