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 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
54 : InsetCollapsable(buf)
56 status_ = par.status();
60 InsetListings::~InsetListings()
62 hideDialogs("listings", this);
66 Inset::DisplayType InsetListings::display() const
68 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
72 void InsetListings::updateBuffer(ParIterator const & it, UpdateType utype)
75 buffer().masterBuffer()->params().documentClass().counters();
76 string const saveflt = cnts.current_float();
78 // Tell to captions what the current float is
79 cnts.current_float("listing");
81 InsetCollapsable::updateBuffer(it, utype);
84 cnts.current_float(saveflt);
88 void InsetListings::write(ostream & os) const
90 os << "listings" << "\n";
91 InsetListingsParams const & par = params();
92 // parameter string is encoded to be a valid lyx token.
93 string opt = par.encodedString();
95 os << "lstparams \"" << opt << "\"\n";
97 os << "inline true\n";
99 os << "inline false\n";
100 InsetCollapsable::write(os);
104 void InsetListings::read(Lexer & lex)
108 string token = lex.getString();
109 if (token == "lstparams") {
111 string const value = lex.getString();
112 params().fromEncodedString(value);
113 } else if (token == "inline") {
115 params().setInline(lex.getBool());
117 // no special option, push back 'status' etc
118 lex.pushToken(token);
122 InsetCollapsable::read(lex);
126 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
128 string param_string = params().params();
129 // NOTE: I use {} to quote text, which is an experimental feature
130 // of the listings package (see page 25 of the manual)
131 bool const isInline = params().isInline();
132 // get the paragraphs. We can not output them directly to given odocstream
133 // because we can not yet determine the delimiter character of \lstinline
136 ParagraphList::const_iterator par = paragraphs().begin();
137 ParagraphList::const_iterator end = paragraphs().end();
139 bool encoding_switched = false;
140 Encoding const * const save_enc = runparams.encoding;
142 if (!runparams.isFullUnicode()
143 && !runparams.encoding->hasFixedWidth()) {
144 // We need to switch to a singlebyte encoding, since the
145 // listings package cannot deal with multi-byte-encoded
146 // glyphs (not needed with full-unicode aware backends
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 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
159 runparams.encoding = lstenc;
160 encoding_switched = true;
164 pos_type siz = par->size();
165 bool captionline = false;
166 for (pos_type i = 0; i < siz; ++i) {
167 if (i == 0 && par->isInset(i) && i + 1 == siz)
169 // ignore all struck out text and (caption) insets
170 if (par->isDeleted(i) || par->isInset(i))
172 char_type c = par->getChar(i);
173 // we can only output characters covered by the current
176 if (runparams.encoding->encodable(c))
178 else if (runparams.dryrun) {
179 code += "<" + _("LyX Warning: ")
180 + _("uncodable character") + " '";
181 code += docstring(1, c);
185 } catch (EncodingException & /* e */) {
186 if (runparams.dryrun) {
187 code += "<" + _("LyX Warning: ")
188 + _("uncodable character") + " '";
189 code += docstring(1, c);
196 // for the inline case, if there are multiple paragraphs
197 // they are simply joined. Otherwise, expect latex errors.
198 if (par != end && !isInline && !captionline)
202 static const docstring delimiters =
203 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
205 size_t pos = delimiters.find_first_not_of(code);
207 // This code piece contains all possible special character? !!!
208 // Replace ! with a warning message and use ! as delimiter.
209 if (pos == string::npos) {
210 docstring delim_error = "<" + _("LyX Warning: ")
211 + _("no more lstline delimiters available") + ">";
212 code = subst(code, from_ascii("!"), delim_error);
214 if (!runparams.dryrun && !runparams.silent) {
215 // FIXME: warning should be passed to the error dialog
216 frontend::Alert::warning(_("Running out of delimiters"),
217 _("For inline program listings, one character must be reserved\n"
218 "as a delimiter. One of the listings, however, uses all available\n"
219 "characters, so none is left for delimiting purposes.\n"
220 "For the time being, I have replaced '!' by a warning, but you\n"
221 "must investigate!"));
224 docstring const delim(1, delimiters[pos]);
226 if (!param_string.empty())
227 os << "[" << from_utf8(param_string) << "]";
228 else if (pos >= delimiters.find('Q'))
229 // We need to terminate the command before the delimiter
231 os << delim << code << delim;
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() && !runparams.silent) {
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 << XHTMLStream::ESCAPE_NONE
281 << caption << html::EndTag("div");
284 InsetLayout const & il = getLayout();
285 string const tag = il.htmltag();
286 string attr = "class ='listings";
287 string const lang = params().getParamValue("language");
291 out << html::StartTag(tag, attr);
292 OutputParams newrp = rp;
293 newrp.html_disable_captions = true;
294 // We don't want to convert dashes here. That's the only conversion we
295 // do for XHTML, so this is safe.
296 newrp.pass_thru = true;
297 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
298 out << html::EndTag(tag);
301 out << html::CompTag("br");
302 // escaping will already have been done
303 os << XHTMLStream::ESCAPE_NONE << ods.str();
305 out << html::EndTag("div");
306 // In this case, this needs to be deferred, but we'll put it
307 // before anything the text itself deferred.
308 def = ods.str() + '\n' + def;
314 string InsetListings::contextMenuName() const
316 return "context-listings";
320 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
322 switch (cmd.action()) {
324 case LFUN_INSET_MODIFY: {
325 cur.recordUndoInset(ATOMIC_UNDO, this);
326 InsetListings::string2params(to_utf8(cmd.argument()), params());
330 case LFUN_INSET_DIALOG_UPDATE:
331 cur.bv().updateDialog("listings", params2string(params()));
335 InsetCollapsable::doDispatch(cur, cmd);
341 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
342 FuncStatus & status) const
344 switch (cmd.action()) {
345 case LFUN_INSET_MODIFY:
346 case LFUN_INSET_DIALOG_UPDATE:
347 status.setEnabled(true);
349 case LFUN_CAPTION_INSERT: {
350 if (params().isInline()) {
351 status.setEnabled(false);
356 return InsetCollapsable::getStatus(cur, cmd, status);
361 docstring const InsetListings::buttonLabel(BufferView const & bv) const
364 if (decoration() == InsetLayout::CLASSIC)
365 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
367 return getNewLabel(_("Listing"));
371 void InsetListings::validate(LaTeXFeatures & features) const
373 features.require("listings");
374 string param_string = params().params();
375 if (param_string.find("\\color") != string::npos)
376 features.require("color");
377 InsetCollapsable::validate(features);
381 bool InsetListings::showInsetDialog(BufferView * bv) const
383 bv->showDialog("listings", params2string(params()),
384 const_cast<InsetListings *>(this));
389 docstring InsetListings::getCaption(OutputParams const & runparams) const
391 if (paragraphs().empty())
394 InsetCaption const * ins = getCaptionInset();
399 odocstringstream ods;
400 otexstream os(ods, texrow);
401 ins->getArgs(os, runparams);
402 ins->getArgument(os, runparams);
403 // the caption may contain \label{} but the listings
404 // package prefer caption={}, label={}
405 docstring cap = ods.str();
406 if (!contains(to_utf8(cap), "\\label{"))
409 // blah1\label{blah2} blah3
411 // blah1 blah3},label={blah2
413 // caption={blah1 blah3},label={blah2}
415 // NOTE that } is not allowed in blah2.
416 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
417 string const new_cap("\\1\\3},label={\\2");
418 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
422 void InsetListings::string2params(string const & in,
423 InsetListingsParams & params)
425 params = InsetListingsParams();
428 istringstream data(in);
431 // discard "listings", which is only used to determine inset
437 string InsetListings::params2string(InsetListingsParams const & params)
440 data << "listings" << ' ';