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"
27 #include "LaTeXFeatures.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "TextClass.h"
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38 #include "support/lassert.h"
40 #include "frontends/alert.h"
41 #include "frontends/Application.h"
43 #include "support/regex.h"
48 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::updateBuffer(ParIterator const & it, UpdateType utype)
78 buffer().masterBuffer()->params().documentClass().counters();
79 string const saveflt = cnts.current_float();
81 // Tell to captions what the current float is
82 cnts.current_float("listing");
84 InsetCollapsable::updateBuffer(it, utype);
87 cnts.current_float(saveflt);
91 void InsetListings::write(ostream & os) const
93 os << "listings" << "\n";
94 InsetListingsParams const & par = params();
95 // parameter string is encoded to be a valid lyx token.
96 string opt = par.encodedString();
98 os << "lstparams \"" << opt << "\"\n";
100 os << "inline true\n";
102 os << "inline false\n";
103 InsetCollapsable::write(os);
107 void InsetListings::read(Lexer & lex)
111 string token = lex.getString();
112 if (token == "lstparams") {
114 string const value = lex.getString();
115 params().fromEncodedString(value);
116 } else if (token == "inline") {
118 params().setInline(lex.getBool());
120 // no special option, push back 'status' etc
121 lex.pushToken(token);
125 InsetCollapsable::read(lex);
129 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
131 string param_string = params().params();
132 // NOTE: I use {} to quote text, which is an experimental feature
133 // of the listings package (see page 25 of the manual)
135 bool const isInline = params().isInline();
136 // get the paragraphs. We can not output them directly to given odocstream
137 // because we can not yet determine the delimiter character of \lstinline
140 ParagraphList::const_iterator par = paragraphs().begin();
141 ParagraphList::const_iterator end = paragraphs().end();
143 bool encoding_switched = false;
144 Encoding const * const save_enc = runparams.encoding;
146 if (runparams.flavor != OutputParams::XETEX
147 && !runparams.encoding->hasFixedWidth()) {
148 // We need to switch to a singlebyte encoding, since the
149 // listings package cannot deal with multi-byte-encoded
150 // glyphs (not needed with XeTeX).
151 Language const * const outer_language =
152 (runparams.local_font != 0) ?
153 runparams.local_font->language()
154 : buffer().params().language;
155 // We try if there's a singlebyte encoding for the current
156 // language; if not, fall back to latin1.
157 Encoding const * const lstenc =
158 (outer_language->encoding()->hasFixedWidth()) ?
159 outer_language->encoding()
160 : encodings.fromLyXName("iso8859-1");
161 pair<bool, int> const c = switchEncoding(os, buffer().params(),
162 runparams, *lstenc, true);
163 runparams.encoding = lstenc;
164 encoding_switched = true;
168 pos_type siz = par->size();
169 bool captionline = false;
170 for (pos_type i = 0; i < siz; ++i) {
171 if (i == 0 && par->isInset(i) && i + 1 == siz)
173 // ignore all struck out text and (caption) insets
174 if (par->isDeleted(i) || par->isInset(i))
176 char_type c = par->getChar(i);
177 // we can only output characters covered by the current
180 if (runparams.encoding->latexChar(c) == docstring(1, c))
182 else if (runparams.dryrun) {
183 code += "<" + _("LyX Warning: ")
184 + _("uncodable character") + " '";
185 code += docstring(1, c);
189 } catch (EncodingException & /* e */) {
190 if (runparams.dryrun) {
191 code += "<" + _("LyX Warning: ")
192 + _("uncodable character") + " '";
193 code += docstring(1, c);
200 // for the inline case, if there are multiple paragraphs
201 // they are simply joined. Otherwise, expect latex errors.
202 if (par != end && !isInline && !captionline) {
208 char const * delimiter = lstinline_delimiters;
209 for (; delimiter != '\0'; ++delimiter)
210 if (!contains(code, *delimiter))
212 // This code piece contains all possible special character? !!!
213 // Replace ! with a warning message and use ! as delimiter.
214 if (*delimiter == '\0') {
215 docstring delim_error = "<" + _("LyX Warning: ")
216 + _("no more lstline delimiters available") + ">";
217 code = subst(code, from_ascii("!"), delim_error);
218 delimiter = lstinline_delimiters;
219 if (!runparams.dryrun) {
220 // FIXME: warning should be passed to the error dialog
221 frontend::Alert::warning(_("Running out of delimiters"),
222 _("For inline program listings, one character must be reserved\n"
223 "as a delimiter. One of the listings, however, uses all available\n"
224 "characters, so none is left for delimiting purposes.\n"
225 "For the time being, I have replaced '!' by a warning, but you\n"
226 "must investigate!"));
229 if (param_string.empty())
230 os << "\\lstinline" << *delimiter;
232 os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
236 OutputParams rp = runparams;
237 rp.moving_arg = true;
238 docstring const caption = getCaption(rp);
239 if (param_string.empty() && caption.empty())
240 os << "\n\\begin{lstlisting}\n";
242 os << "\n\\begin{lstlisting}[";
243 if (!caption.empty()) {
244 os << "caption={" << caption << '}';
245 if (!param_string.empty())
248 os << from_utf8(param_string) << "]\n";
251 os << code << "\n\\end{lstlisting}\n";
255 if (encoding_switched){
257 pair<bool, int> const c = switchEncoding(os, buffer().params(),
258 runparams, *save_enc, true);
259 runparams.encoding = save_enc;
262 if (!uncodable.empty()) {
263 // issue a warning about omitted characters
264 // FIXME: should be passed to the error dialog
265 frontend::Alert::warning(_("Uncodable characters in listings inset"),
266 bformat(_("The following characters in one of the program listings are\n"
267 "not representable in the current encoding and have been omitted:\n%1$s."),
275 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
277 odocstringstream ods;
278 XHTMLStream out(ods);
280 bool const isInline = params().isInline();
282 out << html::CompTag("br");
284 out << html::StartTag("div", "class='float float-listings'");
285 docstring caption = getCaptionHTML(rp);
286 if (!caption.empty())
287 out << html::StartTag("div", "class='float-caption'")
288 << caption << html::EndTag("div");
291 out << html::StartTag("pre");
292 OutputParams newrp = rp;
293 newrp.html_disable_captions = true;
294 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
295 out << html::EndTag("pre");
298 out << html::CompTag("br");
299 // escaping will already have been done
300 os << XHTMLStream::NextRaw() << ods.str();
302 out << html::EndTag("div");
303 // In this case, this needs to be deferred, but we'll put it
304 // before anything the text itself deferred.
305 def = ods.str() + '\n' + def;
311 docstring InsetListings::contextMenu(BufferView const &, int, int) const
313 return from_ascii("context-listings");
317 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
319 switch (cmd.action()) {
321 case LFUN_INSET_MODIFY: {
322 InsetListings::string2params(to_utf8(cmd.argument()), params());
326 case LFUN_INSET_DIALOG_UPDATE:
327 cur.bv().updateDialog("listings", params2string(params()));
331 InsetCollapsable::doDispatch(cur, cmd);
337 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
338 FuncStatus & status) const
340 switch (cmd.action()) {
341 case LFUN_INSET_MODIFY:
342 case LFUN_INSET_DIALOG_UPDATE:
343 status.setEnabled(true);
345 case LFUN_CAPTION_INSERT:
346 status.setEnabled(!params().isInline());
349 return InsetCollapsable::getStatus(cur, cmd, status);
354 docstring const InsetListings::buttonLabel(BufferView const & bv) const
357 if (decoration() == InsetLayout::CLASSIC)
358 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
360 return getNewLabel(_("Listing"));
364 void InsetListings::validate(LaTeXFeatures & features) const
366 features.require("listings");
367 string param_string = params().params();
368 if (param_string.find("\\color") != string::npos)
369 features.require("color");
370 InsetCollapsable::validate(features);
374 bool InsetListings::showInsetDialog(BufferView * bv) const
376 bv->showDialog("listings", params2string(params()),
377 const_cast<InsetListings *>(this));
382 docstring InsetListings::getCaption(OutputParams const & runparams) const
384 if (paragraphs().empty())
387 InsetCaption const * ins = getCaptionInset();
391 odocstringstream ods;
392 ins->getOptArg(ods, runparams);
393 ins->getArgument(ods, runparams);
394 // the caption may contain \label{} but the listings
395 // package prefer caption={}, label={}
396 docstring cap = ods.str();
397 if (!contains(to_utf8(cap), "\\label{"))
400 // blah1\label{blah2} blah3
402 // blah1 blah3},label={blah2
404 // caption={blah1 blah3},label={blah2}
406 // NOTE that } is not allowed in blah2.
407 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
408 string const new_cap("\\1\\3},label={\\2");
409 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
413 void InsetListings::string2params(string const & in,
414 InsetListingsParams & params)
416 params = InsetListingsParams();
419 istringstream data(in);
422 // discard "listings", which is only used to determine inset
428 string InsetListings::params2string(InsetListingsParams const & params)
431 data << "listings" << ' ';