2 * \file InsetListings.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
14 #include "InsetListings.h"
17 #include "BufferView.h"
18 #include "BufferParams.h"
21 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetCaption.h"
28 #include "MetricsInfo.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "TextClass.h"
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/lassert.h"
39 #include "frontends/alert.h"
40 #include "frontends/Application.h"
42 #include <boost/regex.hpp>
47 using namespace lyx::support;
53 char const lstinline_delimiters[] =
54 "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
56 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
57 : InsetCollapsable(buf)
59 status_ = par.status();
63 InsetListings::~InsetListings()
65 hideDialogs("listings", this);
69 Inset::DisplayType InsetListings::display() const
71 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
75 void InsetListings::updateLabels(ParIterator const & it, UpdateType utype)
77 Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
78 string const saveflt = cnts.current_float();
80 // Tell to captions what the current float is
81 cnts.current_float("listing");
83 InsetCollapsable::updateLabels(it, utype);
86 cnts.current_float(saveflt);
90 void InsetListings::write(ostream & os) const
92 os << "listings" << "\n";
93 InsetListingsParams const & par = params();
94 // parameter string is encoded to be a valid lyx token.
95 string opt = par.encodedString();
97 os << "lstparams \"" << opt << "\"\n";
99 os << "inline true\n";
101 os << "inline false\n";
102 InsetCollapsable::write(os);
106 void InsetListings::read(Lexer & lex)
110 string token = lex.getString();
111 if (token == "lstparams") {
113 string const value = lex.getString();
114 params().fromEncodedString(value);
115 } else if (token == "inline") {
117 params().setInline(lex.getBool());
119 // no special option, push back 'status' etc
120 lex.pushToken(token);
124 InsetCollapsable::read(lex);
128 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
130 string param_string = params().params();
131 // NOTE: I use {} to quote text, which is an experimental feature
132 // of the listings package (see page 25 of the manual)
134 bool const isInline = params().isInline();
135 // get the paragraphs. We can not output them directly to given odocstream
136 // because we can not yet determine the delimiter character of \lstinline
139 ParagraphList::const_iterator par = paragraphs().begin();
140 ParagraphList::const_iterator end = paragraphs().end();
142 bool encoding_switched = false;
143 Encoding const * const save_enc = runparams.encoding;
145 if (!runparams.encoding->hasFixedWidth()) {
146 // We need to switch to a singlebyte encoding, since the listings
147 // package cannot deal with multiple-byte-encoded glyphs
148 Language const * const outer_language =
149 (runparams.local_font != 0) ?
150 runparams.local_font->language()
151 : buffer().params().language;
152 // We try if there's a singlebyte encoding for the current
153 // language; if not, fall back to latin1.
154 Encoding const * const lstenc =
155 (outer_language->encoding()->hasFixedWidth()) ?
156 outer_language->encoding()
157 : encodings.fromLyXName("iso8859-1");
158 pair<bool, int> const c = switchEncoding(os, buffer().params(),
159 runparams, *lstenc, true);
160 runparams.encoding = lstenc;
161 encoding_switched = true;
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)
170 // ignore all struck out text and (caption) insets
171 if (par->isDeleted(i) || par->isInset(i))
173 char_type c = par->getChar(i);
174 // we can only output characters covered by the current
177 if (runparams.encoding->latexChar(c) == docstring(1, c))
179 else if (runparams.dryrun) {
180 code += "<" + _("LyX Warning: ")
181 + _("uncodable character") + " '";
182 code += docstring(1, c);
186 } catch (EncodingException & /* e */) {
187 if (runparams.dryrun) {
188 code += "<" + _("LyX Warning: ")
189 + _("uncodable character") + " '";
190 code += docstring(1, c);
197 // for the inline case, if there are multiple paragraphs
198 // they are simply joined. Otherwise, expect latex errors.
199 if (par != end && !isInline && !captionline) {
205 char const * delimiter = lstinline_delimiters;
206 for (; delimiter != '\0'; ++delimiter)
207 if (!contains(code, *delimiter))
209 // This code piece contains all possible special character? !!!
210 // Replace ! with a warning message and use ! as delimiter.
211 if (*delimiter == '\0') {
212 docstring delim_error = "<" + _("LyX Warning: ")
213 + _("no more lstline delimiters available") + ">";
214 code = subst(code, from_ascii("!"), delim_error);
215 delimiter = lstinline_delimiters;
216 if (!runparams.dryrun) {
217 // FIXME: warning should be passed to the error dialog
218 frontend::Alert::warning(_("Running out of delimiters"),
219 _("For inline program listings, one character must be reserved\n"
220 "as a delimiter. One of the listings, however, uses all available\n"
221 "characters, so none is left for delimiting purposes.\n"
222 "For the time being, I have replaced '!' by a warning, but you\n"
223 "must investigate!"));
226 if (param_string.empty())
227 os << "\\lstinline" << *delimiter;
229 os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
233 OutputParams rp = runparams;
234 rp.moving_arg = true;
235 docstring const caption = getCaption(rp);
236 if (param_string.empty() && caption.empty())
237 os << "\n\\begin{lstlisting}\n";
239 os << "\n\\begin{lstlisting}[";
240 if (!caption.empty()) {
241 os << "caption={" << caption << '}';
242 if (!param_string.empty())
245 os << from_utf8(param_string) << "]\n";
248 os << code << "\n\\end{lstlisting}\n";
252 if (encoding_switched){
254 pair<bool, int> const c = switchEncoding(os, buffer().params(),
255 runparams, *save_enc, true);
256 runparams.encoding = save_enc;
259 if (!uncodable.empty()) {
260 // issue a warning about omitted characters
261 // FIXME: should be passed to the error dialog
262 frontend::Alert::warning(_("Uncodable characters in listings inset"),
263 bformat(_("The following characters in one of the program listings are\n"
264 "not representable in the current encoding and have been omitted:\n%1$s."),
272 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
274 odocstringstream ods;
275 XHTMLStream out(ods);
277 bool const isInline = params().isInline();
279 out << html::CompTag("br");
281 out << html::StartTag("div", "class='float float-listings'");
282 docstring caption = getCaptionHTML(rp);
283 if (!caption.empty())
284 out << html::StartTag("div", "class='float-caption'")
285 << caption << html::EndTag("div");
288 out << html::StartTag("pre");
289 OutputParams newrp = rp;
290 newrp.html_disable_captions = true;
291 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
292 out << html::EndTag("pre");
295 out << html::CompTag("br");
296 // escaping will already have been done
297 os << XHTMLStream::NextRaw() << ods.str();
299 out << html::EndTag("div");
300 // In this case, this needs to be deferred, but we'll put it
301 // before anything the text itself deferred.
302 def = ods.str() + '\n' + def;
308 docstring InsetListings::contextMenu(BufferView const &, int, int) const
310 return from_ascii("context-listings");
314 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
316 switch (cmd.action) {
318 case LFUN_INSET_MODIFY: {
319 InsetListings::string2params(to_utf8(cmd.argument()), params());
323 case LFUN_INSET_DIALOG_UPDATE:
324 cur.bv().updateDialog("listings", params2string(params()));
328 InsetCollapsable::doDispatch(cur, cmd);
334 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
335 FuncStatus & status) const
337 switch (cmd.action) {
338 case LFUN_INSET_MODIFY:
339 case LFUN_INSET_DIALOG_UPDATE:
340 status.setEnabled(true);
342 case LFUN_CAPTION_INSERT:
343 status.setEnabled(!params().isInline());
346 return InsetCollapsable::getStatus(cur, cmd, status);
351 docstring const InsetListings::buttonLabel(BufferView const & bv) const
354 if (decoration() == InsetLayout::CLASSIC)
355 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
357 return getNewLabel(_("Listing"));
361 void InsetListings::validate(LaTeXFeatures & features) const
363 features.require("listings");
364 string param_string = params().params();
365 if (param_string.find("\\color") != string::npos)
366 features.require("color");
367 InsetCollapsable::validate(features);
371 bool InsetListings::showInsetDialog(BufferView * bv) const
373 bv->showDialog("listings", params2string(params()),
374 const_cast<InsetListings *>(this));
379 docstring InsetListings::getCaption(OutputParams const & runparams) const
381 if (paragraphs().empty())
384 InsetCaption const * ins = getCaptionInset();
388 odocstringstream ods;
389 ins->getOptArg(ods, runparams);
390 ins->getArgument(ods, runparams);
391 // the caption may contain \label{} but the listings
392 // package prefer caption={}, label={}
393 docstring cap = ods.str();
394 if (!contains(to_utf8(cap), "\\label{"))
397 // blah1\label{blah2} blah3
399 // blah1 blah3},label={blah2
401 // caption={blah1 blah3},label={blah2}
403 // NOTE that } is not allowed in blah2.
404 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
405 string const new_cap("\\1\\3},label={\\2");
406 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
410 void InsetListings::string2params(string const & in,
411 InsetListingsParams & params)
413 params = InsetListingsParams();
416 istringstream data(in);
419 // discard "listings", which is only used to determine inset
425 string InsetListings::params2string(InsetListingsParams const & params)
428 data << "listings" << ' ';