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 : InsetCaptionable(buf,"listing")
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::write(ostream & os) const
74 os << "listings" << "\n";
75 InsetListingsParams const & par = params();
76 // parameter string is encoded to be a valid lyx token.
77 string opt = par.encodedString();
79 os << "lstparams \"" << opt << "\"\n";
81 os << "inline true\n";
83 os << "inline false\n";
84 InsetCaptionable::write(os);
88 void InsetListings::read(Lexer & lex)
92 string token = lex.getString();
93 if (token == "lstparams") {
95 string const value = lex.getString();
96 params().fromEncodedString(value);
97 } else if (token == "inline") {
99 params().setInline(lex.getBool());
101 // no special option, push back 'status' etc
102 lex.pushToken(token);
106 InsetCaptionable::read(lex);
110 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
112 string param_string = params().params();
113 // NOTE: I use {} to quote text, which is an experimental feature
114 // of the listings package (see page 25 of the manual)
115 bool const isInline = params().isInline();
116 // get the paragraphs. We can not output them directly to given odocstream
117 // because we can not yet determine the delimiter character of \lstinline
120 ParagraphList::const_iterator par = paragraphs().begin();
121 ParagraphList::const_iterator end = paragraphs().end();
123 bool encoding_switched = false;
124 Encoding const * const save_enc = runparams.encoding;
125 // The listings package cannot deal with multi-byte-encoded
126 // glyphs, except if full-unicode aware backends
127 // such as XeTeX or LuaTeX are used, and with pLaTeX.
128 bool const multibyte_possible = runparams.isFullUnicode()
129 || (buffer().params().bufferFormat() == "platex"
130 && runparams.encoding->package() == Encoding::japanese);
132 if (!multibyte_possible && !runparams.encoding->hasFixedWidth()) {
133 // We need to switch to a singlebyte encoding, due to
134 // the restrictions of the listings package (see above).
135 // This needs to be consistent with
136 // LaTeXFeatures::getTClassI18nPreamble().
137 Language const * const outer_language =
138 (runparams.local_font != 0) ?
139 runparams.local_font->language()
140 : buffer().params().language;
141 // We try if there's a singlebyte encoding for the current
142 // language; if not, fall back to latin1.
143 Encoding const * const lstenc =
144 (outer_language->encoding()->hasFixedWidth()) ?
145 outer_language->encoding()
146 : encodings.fromLyXName("iso8859-1");
147 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
148 runparams.encoding = lstenc;
149 encoding_switched = true;
153 pos_type siz = par->size();
154 bool captionline = false;
155 for (pos_type i = 0; i < siz; ++i) {
156 if (i == 0 && par->isInset(i) && i + 1 == siz)
158 // ignore all struck out text and (caption) insets
159 if (par->isDeleted(i) || par->isInset(i))
161 char_type c = par->getChar(i);
162 // we can only output characters covered by the current
165 if (runparams.encoding->encodable(c))
167 else if (runparams.dryrun) {
168 code += "<" + _("LyX Warning: ")
169 + _("uncodable character") + " '";
170 code += docstring(1, c);
174 } catch (EncodingException & /* e */) {
175 if (runparams.dryrun) {
176 code += "<" + _("LyX Warning: ")
177 + _("uncodable character") + " '";
178 code += docstring(1, c);
185 // for the inline case, if there are multiple paragraphs
186 // they are simply joined. Otherwise, expect latex errors.
187 if (par != end && !isInline && !captionline)
191 static const docstring delimiters =
192 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
194 size_t pos = delimiters.find_first_not_of(code);
196 // This code piece contains all possible special character? !!!
197 // Replace ! with a warning message and use ! as delimiter.
198 if (pos == string::npos) {
199 docstring delim_error = "<" + _("LyX Warning: ")
200 + _("no more lstline delimiters available") + ">";
201 code = subst(code, from_ascii("!"), delim_error);
203 if (!runparams.dryrun && !runparams.silent) {
204 // FIXME: warning should be passed to the error dialog
205 frontend::Alert::warning(_("Running out of delimiters"),
206 _("For inline program listings, one character must be reserved\n"
207 "as a delimiter. One of the listings, however, uses all available\n"
208 "characters, so none is left for delimiting purposes.\n"
209 "For the time being, I have replaced '!' by a warning, but you\n"
210 "must investigate!"));
213 docstring const delim(1, delimiters[pos]);
215 if (!param_string.empty())
216 os << "[" << from_utf8(param_string) << "]";
217 else if (pos >= delimiters.find('Q'))
218 // We need to terminate the command before the delimiter
220 os << delim << code << delim;
222 OutputParams rp = runparams;
223 rp.moving_arg = true;
224 docstring const caption = getCaption(rp);
225 if (param_string.empty() && caption.empty())
226 os << breakln << "\\begin{lstlisting}\n";
228 os << breakln << "\\begin{lstlisting}[";
229 if (!caption.empty()) {
230 os << "caption={" << caption << '}';
231 if (!param_string.empty())
234 os << from_utf8(param_string) << "]\n";
236 os << code << breakln << "\\end{lstlisting}\n";
239 if (encoding_switched){
241 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
242 runparams.encoding = save_enc;
245 if (!uncodable.empty() && !runparams.silent) {
246 // issue a warning about omitted characters
247 // FIXME: should be passed to the error dialog
248 if (!multibyte_possible && !runparams.encoding->hasFixedWidth())
249 frontend::Alert::warning(_("Uncodable characters in listings inset"),
250 bformat(_("The following characters in one of the program listings are\n"
251 "not representable in the current encoding and have been omitted:\n%1$s.\n"
252 "This is due to a restriction of the listings package, which does\n"
253 "not support your encoding '%2$s'.\n"
254 "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
256 uncodable, _(runparams.encoding->guiName())));
258 frontend::Alert::warning(_("Uncodable characters in listings inset"),
259 bformat(_("The following characters in one of the program listings are\n"
260 "not representable in the current encoding and have been omitted:\n%1$s."),
266 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
268 odocstringstream ods;
269 XHTMLStream out(ods);
271 bool const isInline = params().isInline();
273 out << html::CompTag("br");
275 out << html::StartTag("div", "class='float float-listings'");
276 docstring caption = getCaptionHTML(rp);
277 if (!caption.empty())
278 out << html::StartTag("div", "class='float-caption'")
279 << XHTMLStream::ESCAPE_NONE
280 << caption << html::EndTag("div");
283 InsetLayout const & il = getLayout();
284 string const & tag = il.htmltag();
285 string attr = "class ='listings";
286 string const lang = params().getParamValue("language");
290 out << html::StartTag(tag, attr);
291 OutputParams newrp = rp;
292 newrp.html_disable_captions = true;
293 // We don't want to convert dashes here. That's the only conversion we
294 // do for XHTML, so this is safe.
295 newrp.pass_thru = true;
296 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
297 out << html::EndTag(tag);
300 out << html::CompTag("br");
301 // escaping will already have been done
302 os << XHTMLStream::ESCAPE_NONE << ods.str();
304 out << html::EndTag("div");
305 // In this case, this needs to be deferred, but we'll put it
306 // before anything the text itself deferred.
307 def = ods.str() + '\n' + def;
313 string InsetListings::contextMenuName() const
315 return "context-listings";
319 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
321 switch (cmd.action()) {
323 case LFUN_INSET_MODIFY: {
324 cur.recordUndoInset(this);
325 InsetListings::string2params(to_utf8(cmd.argument()), params());
329 case LFUN_INSET_DIALOG_UPDATE:
330 cur.bv().updateDialog("listings", params2string(params()));
334 InsetCaptionable::doDispatch(cur, cmd);
340 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
341 FuncStatus & status) const
343 switch (cmd.action()) {
344 case LFUN_INSET_MODIFY:
345 case LFUN_INSET_DIALOG_UPDATE:
346 status.setEnabled(true);
348 case LFUN_CAPTION_INSERT: {
349 // the inset outputs at most one caption
350 if (params().isInline() || getCaptionInset()) {
351 status.setEnabled(false);
356 return InsetCaptionable::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 InsetCaptionable::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);
404 // TODO: The code below should be moved to support, and then the test
405 // in ../tests should be moved there as well.
407 // the caption may contain \label{} but the listings
408 // package prefer caption={}, label={}
409 docstring cap = ods.str();
410 if (!contains(to_utf8(cap), "\\label{"))
413 // blah1\label{blah2} blah3
415 // blah1 blah3},label={blah2
417 // caption={blah1 blah3},label={blah2}
419 // NOTE that } is not allowed in blah2.
420 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
421 string const new_cap("$1$3},label={$2");
422 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
426 void InsetListings::string2params(string const & in,
427 InsetListingsParams & params)
429 params = InsetListingsParams();
432 istringstream data(in);
435 // discard "listings", which is only used to determine inset
441 string InsetListings::params2string(InsetListingsParams const & params)
444 data << "listings" << ' ';