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