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