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