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