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 void InsetListings::latex(otexstream & 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)
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.isFullUnicode()
146 && !runparams.encoding->hasFixedWidth()) {
147 // We need to switch to a singlebyte encoding, since the
148 // listings package cannot deal with multi-byte-encoded
149 // glyphs (not needed with full-unicode aware backends
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 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
162 runparams.encoding = lstenc;
163 encoding_switched = true;
167 pos_type siz = par->size();
168 bool captionline = false;
169 for (pos_type i = 0; i < siz; ++i) {
170 if (i == 0 && par->isInset(i) && i + 1 == siz)
172 // ignore all struck out text and (caption) insets
173 if (par->isDeleted(i) || par->isInset(i))
175 char_type c = par->getChar(i);
176 // we can only output characters covered by the current
179 if (runparams.encoding->latexChar(c) == docstring(1, c))
181 else if (runparams.dryrun) {
182 code += "<" + _("LyX Warning: ")
183 + _("uncodable character") + " '";
184 code += docstring(1, c);
188 } catch (EncodingException & /* e */) {
189 if (runparams.dryrun) {
190 code += "<" + _("LyX Warning: ")
191 + _("uncodable character") + " '";
192 code += docstring(1, c);
199 // for the inline case, if there are multiple paragraphs
200 // they are simply joined. Otherwise, expect latex errors.
201 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 << breakln << "\\begin{lstlisting}\n";
239 os << breakln << "\\begin{lstlisting}[";
240 if (!caption.empty()) {
241 os << "caption={" << caption << '}';
242 if (!param_string.empty())
245 os << from_utf8(param_string) << "]\n";
247 os << code << breakln << "\\end{lstlisting}\n";
250 if (encoding_switched){
252 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
253 runparams.encoding = save_enc;
256 if (!uncodable.empty()) {
257 // issue a warning about omitted characters
258 // FIXME: should be passed to the error dialog
259 frontend::Alert::warning(_("Uncodable characters in listings inset"),
260 bformat(_("The following characters in one of the program listings are\n"
261 "not representable in the current encoding and have been omitted:\n%1$s."),
267 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
269 odocstringstream ods;
270 XHTMLStream out(ods);
272 bool const isInline = params().isInline();
274 out << html::CompTag("br");
276 out << html::StartTag("div", "class='float float-listings'");
277 docstring caption = getCaptionHTML(rp);
278 if (!caption.empty())
279 out << html::StartTag("div", "class='float-caption'")
280 << caption << html::EndTag("div");
283 out << html::StartTag("pre");
284 OutputParams newrp = rp;
285 newrp.html_disable_captions = true;
286 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
287 out << html::EndTag("pre");
290 out << html::CompTag("br");
291 // escaping will already have been done
292 os << XHTMLStream::ESCAPE_NONE << ods.str();
294 out << html::EndTag("div");
295 // In this case, this needs to be deferred, but we'll put it
296 // before anything the text itself deferred.
297 def = ods.str() + '\n' + def;
303 docstring InsetListings::contextMenuName() const
305 return from_ascii("context-listings");
309 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
311 switch (cmd.action()) {
313 case LFUN_INSET_MODIFY: {
314 cur.recordUndoInset(ATOMIC_UNDO, this);
315 InsetListings::string2params(to_utf8(cmd.argument()), params());
319 case LFUN_INSET_DIALOG_UPDATE:
320 cur.bv().updateDialog("listings", params2string(params()));
324 InsetCollapsable::doDispatch(cur, cmd);
330 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
331 FuncStatus & status) const
333 switch (cmd.action()) {
334 case LFUN_INSET_MODIFY:
335 case LFUN_INSET_DIALOG_UPDATE:
336 status.setEnabled(true);
338 case LFUN_CAPTION_INSERT:
339 status.setEnabled(!params().isInline());
342 return InsetCollapsable::getStatus(cur, cmd, status);
347 docstring const InsetListings::buttonLabel(BufferView const & bv) const
350 if (decoration() == InsetLayout::CLASSIC)
351 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
353 return getNewLabel(_("Listing"));
357 void InsetListings::validate(LaTeXFeatures & features) const
359 features.require("listings");
360 string param_string = params().params();
361 if (param_string.find("\\color") != string::npos)
362 features.require("color");
363 InsetCollapsable::validate(features);
367 bool InsetListings::showInsetDialog(BufferView * bv) const
369 bv->showDialog("listings", params2string(params()),
370 const_cast<InsetListings *>(this));
375 docstring InsetListings::getCaption(OutputParams const & runparams) const
377 if (paragraphs().empty())
380 InsetCaption const * ins = getCaptionInset();
385 odocstringstream ods;
386 otexstream os(ods, texrow);
387 ins->getOptArg(os, runparams);
388 ins->getArgument(os, runparams);
389 // the caption may contain \label{} but the listings
390 // package prefer caption={}, label={}
391 docstring cap = ods.str();
392 if (!contains(to_utf8(cap), "\\label{"))
395 // blah1\label{blah2} blah3
397 // blah1 blah3},label={blah2
399 // caption={blah1 blah3},label={blah2}
401 // NOTE that } is not allowed in blah2.
402 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
403 string const new_cap("\\1\\3},label={\\2");
404 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
408 void InsetListings::string2params(string const & in,
409 InsetListingsParams & params)
411 params = InsetListingsParams();
414 istringstream data(in);
417 // discard "listings", which is only used to determine inset
423 string InsetListings::params2string(InsetListingsParams const & params)
426 data << "listings" << ' ';