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