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;
126 if (!runparams.isFullUnicode()
127 && !runparams.encoding->hasFixedWidth()) {
128 // We need to switch to a singlebyte encoding, since the
129 // listings package cannot deal with multi-byte-encoded
130 // glyphs (not needed with full-unicode aware backends
132 // This needs to be consistent with
133 // LaTeXFeatures::getTClassI18nPreamble().
134 Language const * const outer_language =
135 (runparams.local_font != 0) ?
136 runparams.local_font->language()
137 : buffer().params().language;
138 // We try if there's a singlebyte encoding for the current
139 // language; if not, fall back to latin1.
140 Encoding const * const lstenc =
141 (outer_language->encoding()->hasFixedWidth()) ?
142 outer_language->encoding()
143 : encodings.fromLyXName("iso8859-1");
144 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
145 runparams.encoding = lstenc;
146 encoding_switched = true;
150 pos_type siz = par->size();
151 bool captionline = false;
152 for (pos_type i = 0; i < siz; ++i) {
153 if (i == 0 && par->isInset(i) && i + 1 == siz)
155 // ignore all struck out text and (caption) insets
156 if (par->isDeleted(i) || par->isInset(i))
158 char_type c = par->getChar(i);
159 // we can only output characters covered by the current
162 if (runparams.encoding->encodable(c))
164 else if (runparams.dryrun) {
165 code += "<" + _("LyX Warning: ")
166 + _("uncodable character") + " '";
167 code += docstring(1, c);
171 } catch (EncodingException & /* e */) {
172 if (runparams.dryrun) {
173 code += "<" + _("LyX Warning: ")
174 + _("uncodable character") + " '";
175 code += docstring(1, c);
182 // for the inline case, if there are multiple paragraphs
183 // they are simply joined. Otherwise, expect latex errors.
184 if (par != end && !isInline && !captionline)
188 static const docstring delimiters =
189 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
191 size_t pos = delimiters.find_first_not_of(code);
193 // This code piece contains all possible special character? !!!
194 // Replace ! with a warning message and use ! as delimiter.
195 if (pos == string::npos) {
196 docstring delim_error = "<" + _("LyX Warning: ")
197 + _("no more lstline delimiters available") + ">";
198 code = subst(code, from_ascii("!"), delim_error);
200 if (!runparams.dryrun && !runparams.silent) {
201 // FIXME: warning should be passed to the error dialog
202 frontend::Alert::warning(_("Running out of delimiters"),
203 _("For inline program listings, one character must be reserved\n"
204 "as a delimiter. One of the listings, however, uses all available\n"
205 "characters, so none is left for delimiting purposes.\n"
206 "For the time being, I have replaced '!' by a warning, but you\n"
207 "must investigate!"));
210 docstring const delim(1, delimiters[pos]);
212 if (!param_string.empty())
213 os << "[" << from_utf8(param_string) << "]";
214 else if (pos >= delimiters.find('Q'))
215 // We need to terminate the command before the delimiter
217 os << delim << code << delim;
219 OutputParams rp = runparams;
220 rp.moving_arg = true;
221 docstring const caption = getCaption(rp);
222 if (param_string.empty() && caption.empty())
223 os << breakln << "\\begin{lstlisting}\n";
225 os << breakln << "\\begin{lstlisting}[";
226 if (!caption.empty()) {
227 os << "caption={" << caption << '}';
228 if (!param_string.empty())
231 os << from_utf8(param_string) << "]\n";
233 os << code << breakln << "\\end{lstlisting}\n";
236 if (encoding_switched){
238 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
239 runparams.encoding = save_enc;
242 if (!uncodable.empty() && !runparams.silent) {
243 // issue a warning about omitted characters
244 // FIXME: should be passed to the error dialog
245 frontend::Alert::warning(_("Uncodable characters in listings inset"),
246 bformat(_("The following characters in one of the program listings are\n"
247 "not representable in the current encoding and have been omitted:\n%1$s."),
253 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
255 odocstringstream ods;
256 XHTMLStream out(ods);
258 bool const isInline = params().isInline();
260 out << html::CompTag("br");
262 out << html::StartTag("div", "class='float float-listings'");
263 docstring caption = getCaptionHTML(rp);
264 if (!caption.empty())
265 out << html::StartTag("div", "class='float-caption'")
266 << XHTMLStream::ESCAPE_NONE
267 << caption << html::EndTag("div");
270 InsetLayout const & il = getLayout();
271 string const & tag = il.htmltag();
272 string attr = "class ='listings";
273 string const lang = params().getParamValue("language");
277 out << html::StartTag(tag, attr);
278 OutputParams newrp = rp;
279 newrp.html_disable_captions = true;
280 // We don't want to convert dashes here. That's the only conversion we
281 // do for XHTML, so this is safe.
282 newrp.pass_thru = true;
283 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
284 out << html::EndTag(tag);
287 out << html::CompTag("br");
288 // escaping will already have been done
289 os << XHTMLStream::ESCAPE_NONE << ods.str();
291 out << html::EndTag("div");
292 // In this case, this needs to be deferred, but we'll put it
293 // before anything the text itself deferred.
294 def = ods.str() + '\n' + def;
300 string InsetListings::contextMenuName() const
302 return "context-listings";
306 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
308 switch (cmd.action()) {
310 case LFUN_INSET_MODIFY: {
311 cur.recordUndoInset(this);
312 InsetListings::string2params(to_utf8(cmd.argument()), params());
316 case LFUN_INSET_DIALOG_UPDATE:
317 cur.bv().updateDialog("listings", params2string(params()));
321 InsetCaptionable::doDispatch(cur, cmd);
327 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
328 FuncStatus & status) const
330 switch (cmd.action()) {
331 case LFUN_INSET_MODIFY:
332 case LFUN_INSET_DIALOG_UPDATE:
333 status.setEnabled(true);
335 case LFUN_CAPTION_INSERT: {
336 // the inset outputs at most one caption
337 if (params().isInline() || getCaptionInset()) {
338 status.setEnabled(false);
343 return InsetCaptionable::getStatus(cur, cmd, status);
348 docstring const InsetListings::buttonLabel(BufferView const & bv) const
351 if (decoration() == InsetLayout::CLASSIC)
352 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
354 return getNewLabel(_("Listing"));
358 void InsetListings::validate(LaTeXFeatures & features) const
360 features.require("listings");
361 string param_string = params().params();
362 if (param_string.find("\\color") != string::npos)
363 features.require("color");
364 InsetCaptionable::validate(features);
368 bool InsetListings::showInsetDialog(BufferView * bv) const
370 bv->showDialog("listings", params2string(params()),
371 const_cast<InsetListings *>(this));
376 docstring InsetListings::getCaption(OutputParams const & runparams) const
378 if (paragraphs().empty())
381 InsetCaption const * ins = getCaptionInset();
386 odocstringstream ods;
387 otexstream os(ods, texrow);
388 ins->getArgs(os, runparams);
389 ins->getArgument(os, runparams);
390 // the caption may contain \label{} but the listings
391 // package prefer caption={}, label={}
392 docstring cap = ods.str();
393 if (!contains(to_utf8(cap), "\\label{"))
396 // blah1\label{blah2} blah3
398 // blah1 blah3},label={blah2
400 // caption={blah1 blah3},label={blah2}
402 // NOTE that } is not allowed in blah2.
403 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
404 string const new_cap("\\1\\3},label={\\2");
405 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
409 void InsetListings::string2params(string const & in,
410 InsetListingsParams & params)
412 params = InsetListingsParams();
415 istringstream data(in);
418 // discard "listings", which is only used to determine inset
424 string InsetListings::params2string(InsetListingsParams const & params)
427 data << "listings" << ' ';