]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
2d9fc167960a8c00cbd5ea3cf63573727ff51447
[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 #include "InsetCaption.h"
16
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "Counters.h"
20 #include "Cursor.h"
21 #include "DispatchResult.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
24 #include "support/gettext.h"
25 #include "InsetList.h"
26 #include "Language.h"
27 #include "MetricsInfo.h"
28 #include "TextClass.h"
29
30 #include "support/docstream.h"
31 #include "support/lstrings.h"
32
33 #include <sstream>
34
35 using std::istringstream;
36 using std::ostream;
37 using std::ostringstream;
38 using std::string;
39
40 namespace lyx {
41
42 using support::token;
43 using support::contains;
44 using support::subst;
45
46 char const lstinline_delimiters[] =
47         "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
48
49 InsetListings::InsetListings(BufferParams const & bp, InsetListingsParams const & par)
50         : InsetCollapsable(bp, par.status())
51 {}
52
53
54 InsetListings::InsetListings(InsetListings const & in)
55         : InsetCollapsable(in), params_(in.params_)
56 {}
57
58
59 Inset * InsetListings::clone() const
60 {
61         return new InsetListings(*this);
62 }
63
64
65 InsetListings::~InsetListings()
66 {
67         InsetListingsMailer(*this).hideDialog();
68 }
69
70
71 Inset::DisplayType InsetListings::display() const
72 {
73         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
74 }
75
76
77 void InsetListings::updateLabels(Buffer const & buf, ParIterator const & it)
78 {
79         Counters & cnts = buf.params().getTextClass().counters();
80         string const saveflt = cnts.current_float();
81
82         // Tell to captions what the current float is
83         cnts.current_float("listing");
84
85         InsetCollapsable::updateLabels(buf, it);
86
87         //reset afterwards
88         cnts.current_float(saveflt);
89 }
90
91
92 void InsetListings::write(Buffer const & buf, ostream & os) const
93 {
94         os << "listings" << "\n";
95         InsetListingsParams const & par = params();
96         // parameter string is encoded to be a valid lyx token.
97         string opt = par.encodedString();
98         if (!opt.empty())
99                 os << "lstparams \"" << opt << "\"\n";
100         if (par.isInline())
101                 os << "inline true\n";
102         else
103                 os << "inline false\n";
104         InsetCollapsable::write(buf, os);
105 }
106
107
108 void InsetListings::read(Buffer const & buf, Lexer & lex)
109 {
110         while (lex.isOK()) {
111                 lex.next();
112                 string const token = lex.getString();
113                 if (token == "lstparams") {
114                         lex.next();
115                         string const value = lex.getString();
116                         params().fromEncodedString(value);
117                 } else if (token == "inline") {
118                         lex.next();
119                         params().setInline(lex.getBool());
120                 } else {
121                         // no special option, push back 'status' etc
122                         lex.pushToken(token);
123                         break;
124                 }
125         }
126         InsetCollapsable::read(buf, lex);
127 }
128
129
130 docstring const InsetListings::editMessage() const
131 {
132         return _("Opened Listing Inset");
133 }
134
135
136 int InsetListings::latex(Buffer const & buf, odocstream & os,
137                     OutputParams const & runparams) const
138 {
139         string param_string = params().params();
140         // NOTE: I use {} to quote text, which is an experimental feature
141         // of the listings package (see page 25 of the manual)
142         int lines = 0;
143         bool isInline = params().isInline();
144         // get the paragraphs. We can not output them directly to given odocstream
145         // because we can not yet determine the delimiter character of \lstinline
146         docstring code;
147         ParagraphList::const_iterator par = paragraphs().begin();
148         ParagraphList::const_iterator end = paragraphs().end();
149
150         while (par != end) {
151                 pos_type siz = par->size();
152                 bool captionline = false;
153                 for (pos_type i = 0; i < siz; ++i) {
154                         if (i == 0 && par->isInset(i) && i + 1 == siz)
155                                 captionline = true;
156                         // ignore all struck out text and (caption) insets
157                         if (par->isDeleted(i) || par->isInset(i))
158                                 continue;
159                         code += par->getChar(i);
160                 }
161                 ++par;
162                 // for the inline case, if there are multiple paragraphs
163                 // they are simply joined. Otherwise, expect latex errors.
164                 if (par != end && !isInline && !captionline) {
165                         code += "\n";
166                         ++lines;
167                 }
168         }
169         if (isInline) {
170                 char const * delimiter = lstinline_delimiters;
171                 for (; delimiter != '\0'; ++delimiter)
172                         if (!contains(code, *delimiter))
173                                 break;
174                 // This code piece contains all possible special character? !!!
175                 // Replace ! with a warning message and use ! as delimiter.
176                 if (*delimiter == '\0') {
177                         code = subst(code, from_ascii("!"), from_ascii(" WARNING: no lstline delimiter can be used "));
178                         delimiter = lstinline_delimiters;
179                 }
180                 if (param_string.empty())
181                         os << "\\lstinline" << *delimiter;
182                 else
183                         os << "\\lstinline[" << from_ascii(param_string) << "]" << *delimiter;
184                 os << code
185                    << *delimiter;
186         } else {
187                 OutputParams rp = runparams;
188                 // FIXME: the line below would fix bug 4182,
189                 // but real_current_font moved to cursor.
190                 //rp.local_font = &text_.real_current_font;
191                 rp.moving_arg = true;
192                 docstring const caption = getCaption(buf, rp);
193                 runparams.encoding = rp.encoding;
194                 if (param_string.empty() && caption.empty())
195                         os << "\n\\begingroup\n\\inputencoding{latin1}\n\\begin{lstlisting}\n";
196                 else {
197                         os << "\n\\begingroup\n\\inputencoding{latin1}\n\\begin{lstlisting}[";
198                         if (!caption.empty()) {
199                                 os << "caption={" << caption << '}';
200                                 if (!param_string.empty())
201                                         os << ',';
202                         }
203                         os << from_utf8(param_string) << "]\n";
204                 }
205                 lines += 4;
206                 os << code << "\n\\end{lstlisting}\n\\endgroup\n";
207                 lines += 3;
208         }
209
210         return lines;
211 }
212
213
214 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
215 {
216         switch (cmd.action) {
217
218         case LFUN_INSET_MODIFY: {
219                 InsetListingsMailer::string2params(to_utf8(cmd.argument()), params());
220                 break;
221         }
222         case LFUN_INSET_DIALOG_UPDATE:
223                 InsetListingsMailer(*this).updateDialog(&cur.bv());
224                 break;
225         case LFUN_MOUSE_RELEASE: {
226                 if (cmd.button() == mouse_button::button3 && hitButton(cmd)) {
227                         InsetListingsMailer(*this).showDialog(&cur.bv());
228                         break;
229                 }
230                 InsetCollapsable::doDispatch(cur, cmd);
231                 break;
232         }
233         default:
234                 InsetCollapsable::doDispatch(cur, cmd);
235                 break;
236         }
237 }
238
239
240 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
241         FuncStatus & status) const
242 {
243         switch (cmd.action) {
244                 case LFUN_INSET_DIALOG_UPDATE:
245                         status.enabled(true);
246                         return true;
247                 case LFUN_CAPTION_INSERT:
248                         status.enabled(!params().isInline());
249                         return true;
250                 default:
251                         return InsetCollapsable::getStatus(cur, cmd, status);
252         }
253 }
254
255
256 void InsetListings::setButtonLabel()
257 {
258         // FIXME UNICODE
259         if (decoration() == Classic)
260                 setLabel(isOpen() ?  _("Listing") : getNewLabel(_("Listing")));
261         else
262                 setLabel(getNewLabel(_("Listing")));
263 }
264
265
266 void InsetListings::validate(LaTeXFeatures & features) const
267 {
268         features.require("listings");
269         InsetCollapsable::validate(features);
270 }
271
272
273 bool InsetListings::showInsetDialog(BufferView * bv) const
274 {
275         InsetListingsMailer(const_cast<InsetListings &>(*this)).showDialog(bv);
276         return true;
277 }
278
279
280 docstring InsetListings::getCaption(Buffer const & buf,
281         OutputParams const & runparams) const
282 {
283         if (paragraphs().empty())
284                 return docstring();
285
286         ParagraphList::const_iterator pit = paragraphs().begin();
287         for (; pit != paragraphs().end(); ++pit) {
288                 InsetList::const_iterator it = pit->insetList().begin();
289                 for (; it != pit->insetList().end(); ++it) {
290                         Inset & inset = *it->inset;
291                         if (inset.lyxCode() == CAPTION_CODE) {
292                                 odocstringstream ods;
293                                 InsetCaption * ins =
294                                         static_cast<InsetCaption *>(it->inset);
295                                 ins->getOptArg(buf, ods, runparams);
296                                 ins->getArgument(buf, ods, runparams);
297                                 return ods.str();
298                         }
299                 }
300         }
301         return docstring();
302 }
303
304
305 string const InsetListingsMailer::name_("listings");
306
307 InsetListingsMailer::InsetListingsMailer(InsetListings & inset)
308         : inset_(inset)
309 {}
310
311
312 string const InsetListingsMailer::inset2string(Buffer const &) const
313 {
314         return params2string(inset_.params());
315 }
316
317
318 void InsetListingsMailer::string2params(string const & in,
319                                    InsetListingsParams & params)
320 {
321         params = InsetListingsParams();
322         if (in.empty())
323                 return;
324         istringstream data(in);
325         Lexer lex(0, 0);
326         lex.setStream(data);
327         // discard "listings", which is only used to determine inset
328         lex.next();
329         params.read(lex);
330 }
331
332
333 string const
334 InsetListingsMailer::params2string(InsetListingsParams const & params)
335 {
336         ostringstream data;
337         data << name_ << " ";
338         params.write(data);
339         return data.str();
340 }
341
342
343 } // namespace lyx