LyX 1.5.0 is released
[lyx.git] / src / insets / InsetInclude.cpp
blob90f776e2152e7dfd3392c7d1e06873b0b1937582
1 /**
2 * \file InsetInclude.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
9 */
11 #include <config.h>
13 #include "InsetInclude.h"
15 #include "Buffer.h"
16 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
20 #include "Cursor.h"
21 #include "debug.h"
22 #include "DispatchResult.h"
23 #include "Exporter.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "gettext.h"
27 #include "LaTeXFeatures.h"
28 #include "LyX.h"
29 #include "LyXRC.h"
30 #include "Lexer.h"
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
33 #include "TocBackend.h"
35 #include "frontends/alert.h"
36 #include "frontends/Painter.h"
38 #include "graphics/PreviewImage.h"
39 #include "graphics/PreviewLoader.h"
41 #include "insets/RenderPreview.h"
42 #include "insets/InsetListingsParams.h"
44 #include "support/filetools.h"
45 #include "support/lstrings.h" // contains
46 #include "support/lyxalgo.h"
47 #include "support/lyxlib.h"
48 #include "support/convert.h"
50 #include <boost/bind.hpp>
51 #include <boost/filesystem/operations.hpp>
54 namespace lyx {
56 // Implementation is in LyX.cpp
57 extern void dispatch(FuncRequest const & action);
59 using support::addName;
60 using support::absolutePath;
61 using support::bformat;
62 using support::changeExtension;
63 using support::contains;
64 using support::copy;
65 using support::DocFileName;
66 using support::FileName;
67 using support::getFileContents;
68 using support::getVectorFromString;
69 using support::isFileReadable;
70 using support::isLyXFilename;
71 using support::isValidLaTeXFilename;
72 using support::latex_path;
73 using support::makeAbsPath;
74 using support::makeDisplayPath;
75 using support::makeRelPath;
76 using support::onlyFilename;
77 using support::onlyPath;
78 using support::prefixIs;
79 using support::subst;
80 using support::sum;
82 using std::endl;
83 using std::string;
84 using std::auto_ptr;
85 using std::istringstream;
86 using std::ostream;
87 using std::ostringstream;
88 using std::vector;
90 namespace Alert = frontend::Alert;
91 namespace fs = boost::filesystem;
94 namespace {
96 docstring const uniqueID()
98 static unsigned int seed = 1000;
99 return "file" + convert<docstring>(++seed);
103 bool isListings(InsetCommandParams const & params)
105 return params.getCmdName() == "lstinputlisting";
108 } // namespace anon
111 InsetInclude::InsetInclude(InsetCommandParams const & p)
112 : params_(p), include_label(uniqueID()),
113 preview_(new RenderMonitoredPreview(this)),
114 set_label_(false), counter_(0)
116 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
120 InsetInclude::InsetInclude(InsetInclude const & other)
121 : Inset(other),
122 params_(other.params_),
123 include_label(other.include_label),
124 preview_(new RenderMonitoredPreview(this)),
125 set_label_(false), counter_(0)
127 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
131 InsetInclude::~InsetInclude()
133 InsetIncludeMailer(*this).hideDialog();
137 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
139 switch (cmd.action) {
141 case LFUN_INSET_MODIFY: {
142 InsetCommandParams p("include");
143 InsetIncludeMailer::string2params(to_utf8(cmd.argument()), p);
144 if (!p.getCmdName().empty()) {
145 if (isListings(p)){
146 InsetListingsParams par_old(params().getOptions());
147 InsetListingsParams par_new(p.getOptions());
148 if (par_old.getParamValue("label") !=
149 par_new.getParamValue("label")
150 && !par_new.getParamValue("label").empty())
151 cur.bv().buffer()->changeRefsIfUnique(
152 from_utf8(par_old.getParamValue("label")),
153 from_utf8(par_new.getParamValue("label")),
154 Inset::REF_CODE);
156 set(p, cur.buffer());
157 cur.buffer().updateBibfilesCache();
158 } else
159 cur.noUpdate();
160 break;
163 case LFUN_INSET_DIALOG_UPDATE:
164 InsetIncludeMailer(*this).updateDialog(&cur.bv());
165 break;
167 case LFUN_MOUSE_RELEASE:
168 if (!cur.selection())
169 InsetIncludeMailer(*this).showDialog(&cur.bv());
170 break;
172 default:
173 Inset::doDispatch(cur, cmd);
174 break;
179 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
180 FuncStatus & flag) const
182 switch (cmd.action) {
184 case LFUN_INSET_MODIFY:
185 case LFUN_INSET_DIALOG_UPDATE:
186 flag.enabled(true);
187 return true;
189 default:
190 return Inset::getStatus(cur, cmd, flag);
195 InsetCommandParams const & InsetInclude::params() const
197 return params_;
201 namespace {
203 /// the type of inclusion
204 enum Types {
205 INCLUDE = 0,
206 VERB = 1,
207 INPUT = 2,
208 VERBAST = 3,
209 LISTINGS = 4,
213 Types type(InsetCommandParams const & params)
215 string const command_name = params.getCmdName();
217 if (command_name == "input")
218 return INPUT;
219 if (command_name == "verbatiminput")
220 return VERB;
221 if (command_name == "verbatiminput*")
222 return VERBAST;
223 if (command_name == "lstinputlisting")
224 return LISTINGS;
225 return INCLUDE;
229 bool isVerbatim(InsetCommandParams const & params)
231 string const command_name = params.getCmdName();
232 return command_name == "verbatiminput" ||
233 command_name == "verbatiminput*";
237 bool isInputOrInclude(InsetCommandParams const & params)
239 Types const t = type(params);
240 return (t == INPUT) || (t == INCLUDE);
244 string const masterFilename(Buffer const & buffer)
246 return buffer.getMasterBuffer()->fileName();
250 string const parentFilename(Buffer const & buffer)
252 return buffer.fileName();
256 FileName const includedFilename(Buffer const & buffer,
257 InsetCommandParams const & params)
259 return makeAbsPath(to_utf8(params["filename"]),
260 onlyPath(parentFilename(buffer)));
264 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
266 } // namespace anon
269 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
271 params_ = p;
272 set_label_ = false;
274 if (preview_->monitoring())
275 preview_->stopMonitoring();
277 if (type(params_) == INPUT)
278 add_preview(*preview_, *this, buffer);
282 auto_ptr<Inset> InsetInclude::doClone() const
284 return auto_ptr<Inset>(new InsetInclude(*this));
288 void InsetInclude::write(Buffer const &, ostream & os) const
290 write(os);
294 void InsetInclude::write(ostream & os) const
296 os << "Include " << to_utf8(params_.getCommand()) << '\n'
297 << "preview " << convert<string>(params_.preview()) << '\n';
301 void InsetInclude::read(Buffer const &, Lexer & lex)
303 read(lex);
307 void InsetInclude::read(Lexer & lex)
309 if (lex.isOK()) {
310 lex.eatLine();
311 string const command = lex.getString();
312 params_.scanCommand(command);
314 string token;
315 while (lex.isOK()) {
316 lex.next();
317 token = lex.getString();
318 if (token == "\\end_inset")
319 break;
320 if (token == "preview") {
321 lex.next();
322 params_.preview(lex.getBool());
323 } else
324 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
326 if (token != "\\end_inset") {
327 lex.printError("Missing \\end_inset at this point. "
328 "Read: `$$Token'");
333 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
335 docstring temp;
337 switch (type(params_)) {
338 case INPUT:
339 temp += buf.B_("Input");
340 break;
341 case VERB:
342 temp += buf.B_("Verbatim Input");
343 break;
344 case VERBAST:
345 temp += buf.B_("Verbatim Input*");
346 break;
347 case INCLUDE:
348 temp += buf.B_("Include");
349 break;
350 case LISTINGS: {
351 if (counter_ > 0)
352 temp += buf.B_("Program Listing ") + convert<docstring>(counter_);
353 else
354 temp += buf.B_("Program Listing");
355 break;
359 temp += ": ";
361 if (params_["filename"].empty())
362 temp += "???";
363 else
364 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
366 return temp;
370 namespace {
372 /// return the child buffer if the file is a LyX doc and is loaded
373 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
375 if (isVerbatim(params) || isListings(params))
376 return 0;
378 string const included_file = includedFilename(buffer, params).absFilename();
379 if (!isLyXFilename(included_file))
380 return 0;
382 Buffer * childBuffer = theBufferList().getBuffer(included_file);
384 //FIXME RECURSIVE INCLUDES
385 if (childBuffer == & buffer)
386 return 0;
387 else
388 return childBuffer;
392 /// return true if the file is or got loaded.
393 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
395 if (isVerbatim(params) || isListings(params))
396 return false;
398 FileName const included_file = includedFilename(buffer, params);
399 if (!isLyXFilename(included_file.absFilename()))
400 return false;
402 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
403 if (!buf) {
404 // the readonly flag can/will be wrong, not anymore I think.
405 if (!fs::exists(included_file.toFilesystemEncoding()))
406 return false;
407 if (use_gui) {
408 lyx::dispatch(FuncRequest(LFUN_BUFFER_CHILD_OPEN,
409 included_file.absFilename() + "|true"));
410 buf = theBufferList().getBuffer(included_file.absFilename());
412 else {
413 buf = theBufferList().newBuffer(included_file.absFilename());
414 if (!loadLyXFile(buf, included_file)) {
415 //close the buffer we just opened
416 theBufferList().close(buf, false);
417 return false;
420 return buf;
422 buf->setParentName(parentFilename(buffer));
423 return true;
427 } // namespace anon
430 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
431 OutputParams const & runparams) const
433 string incfile(to_utf8(params_["filename"]));
435 // Do nothing if no file name has been specified
436 if (incfile.empty())
437 return 0;
439 FileName const included_file(includedFilename(buffer, params_));
441 //Check we're not trying to include ourselves.
442 //FIXME RECURSIVE INCLUDE
443 //This isn't sufficient, as the inclusion could be downstream.
444 //But it'll have to do for now.
445 if (isInputOrInclude(params_) &&
446 buffer.fileName() == included_file.absFilename())
448 Alert::error(_("Recursive input"),
449 bformat(_("Attempted to include file %1$s in itself! "
450 "Ignoring inclusion."), from_utf8(incfile)));
451 return 0;
454 Buffer const * const m_buffer = buffer.getMasterBuffer();
456 // if incfile is relative, make it relative to the master
457 // buffer directory.
458 if (!absolutePath(incfile)) {
459 // FIXME UNICODE
460 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
461 from_utf8(m_buffer->filePath())));
464 // write it to a file (so far the complete file)
465 string const exportfile = changeExtension(incfile, ".tex");
466 string const mangled =
467 DocFileName(changeExtension(included_file.absFilename(),".tex")).
468 mangledFilename();
469 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
471 if (!runparams.nice)
472 incfile = mangled;
473 else if (!isValidLaTeXFilename(incfile)) {
474 frontend::Alert::warning(_("Invalid filename"),
475 _("The following filename is likely to cause trouble "
476 "when running the exported file through LaTeX: ") +
477 from_utf8(incfile));
479 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
480 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
481 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
483 if (runparams.inComment || runparams.dryrun) {
484 //Don't try to load or copy the file if we're
485 //in a comment or doing a dryrun
486 } else if (isInputOrInclude(params_) &&
487 isLyXFilename(included_file.absFilename())) {
488 //if it's a LyX file and we're inputting or including,
489 //try to load it so we can write the associated latex
490 if (!loadIfNeeded(buffer, params_))
491 return false;
493 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
495 if (tmp->params().textclass != m_buffer->params().textclass) {
496 // FIXME UNICODE
497 docstring text = bformat(_("Included file `%1$s'\n"
498 "has textclass `%2$s'\n"
499 "while parent file has textclass `%3$s'."),
500 makeDisplayPath(included_file.absFilename()),
501 from_utf8(tmp->params().getTextClass().name()),
502 from_utf8(m_buffer->params().getTextClass().name()));
503 Alert::warning(_("Different textclasses"), text);
504 //return 0;
507 tmp->markDepClean(m_buffer->temppath());
509 #ifdef WITH_WARNINGS
510 #warning handle non existing files
511 #warning Second argument is irrelevant!
512 // since only_body is true, makeLaTeXFile will not look at second
513 // argument. Should we set it to string(), or should makeLaTeXFile
514 // make use of it somehow? (JMarc 20031002)
515 #endif
516 // The included file might be written in a different encoding
517 Encoding const * const oldEnc = runparams.encoding;
518 runparams.encoding = &tmp->params().encoding();
519 tmp->makeLaTeXFile(writefile,
520 onlyPath(masterFilename(buffer)),
521 runparams, false);
522 runparams.encoding = oldEnc;
523 } else {
524 // In this case, it's not a LyX file, so we copy the file
525 // to the temp dir, so that .aux files etc. are not created
526 // in the original dir. Files included by this file will be
527 // found via input@path, see ../Buffer.cpp.
528 unsigned long const checksum_in = sum(included_file);
529 unsigned long const checksum_out = sum(writefile);
531 if (checksum_in != checksum_out) {
532 if (!copy(included_file, writefile)) {
533 // FIXME UNICODE
534 LYXERR(Debug::LATEX)
535 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
536 "into the temporary directory."),
537 from_utf8(included_file.absFilename())))
538 << endl;
539 return 0;
544 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
545 "latex" : "pdflatex";
546 if (isVerbatim(params_)) {
547 incfile = latex_path(incfile);
548 // FIXME UNICODE
549 os << '\\' << from_ascii(params_.getCmdName()) << '{'
550 << from_utf8(incfile) << '}';
551 } else if (type(params_) == INPUT) {
552 runparams.exportdata->addExternalFile(tex_format, writefile,
553 exportfile);
555 // \input wants file with extension (default is .tex)
556 if (!isLyXFilename(included_file.absFilename())) {
557 incfile = latex_path(incfile);
558 // FIXME UNICODE
559 os << '\\' << from_ascii(params_.getCmdName())
560 << '{' << from_utf8(incfile) << '}';
561 } else {
562 incfile = changeExtension(incfile, ".tex");
563 incfile = latex_path(incfile);
564 // FIXME UNICODE
565 os << '\\' << from_ascii(params_.getCmdName())
566 << '{' << from_utf8(incfile) << '}';
568 } else if (type(params_) == LISTINGS) {
569 os << '\\' << from_ascii(params_.getCmdName());
570 string opt = params_.getOptions();
571 // opt is set in QInclude dialog and should have passed validation.
572 InsetListingsParams params(opt);
573 if (!params.params().empty())
574 os << "[" << from_utf8(params.params()) << "]";
575 os << '{' << from_utf8(incfile) << '}';
576 } else {
577 runparams.exportdata->addExternalFile(tex_format, writefile,
578 exportfile);
580 // \include don't want extension and demands that the
581 // file really have .tex
582 incfile = changeExtension(incfile, string());
583 incfile = latex_path(incfile);
584 // FIXME UNICODE
585 os << '\\' << from_ascii(params_.getCmdName()) << '{'
586 << from_utf8(incfile) << '}';
589 return 0;
593 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
594 OutputParams const &) const
596 if (isVerbatim(params_) || isListings(params_)) {
597 os << '[' << getScreenLabel(buffer) << '\n';
598 // FIXME: We don't know the encoding of the file
599 docstring const str =
600 from_utf8(getFileContents(includedFilename(buffer, params_)));
601 os << str;
602 os << "\n]";
603 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
604 } else {
605 docstring const str = '[' + getScreenLabel(buffer) + ']';
606 os << str;
607 return str.size();
612 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
613 OutputParams const & runparams) const
615 string incfile = to_utf8(params_["filename"]);
617 // Do nothing if no file name has been specified
618 if (incfile.empty())
619 return 0;
621 string const included_file = includedFilename(buffer, params_).absFilename();
623 //Check we're not trying to include ourselves.
624 //FIXME RECURSIVE INCLUDE
625 //This isn't sufficient, as the inclusion could be downstream.
626 //But it'll have to do for now.
627 if (buffer.fileName() == included_file) {
628 Alert::error(_("Recursive input"),
629 bformat(_("Attempted to include file %1$s in itself! "
630 "Ignoring inclusion."), from_utf8(incfile)));
631 return 0;
634 // write it to a file (so far the complete file)
635 string const exportfile = changeExtension(incfile, ".sgml");
636 DocFileName writefile(changeExtension(included_file, ".sgml"));
638 if (loadIfNeeded(buffer, params_)) {
639 Buffer * tmp = theBufferList().getBuffer(included_file);
641 string const mangled = writefile.mangledFilename();
642 writefile = makeAbsPath(mangled,
643 buffer.getMasterBuffer()->temppath());
644 if (!runparams.nice)
645 incfile = mangled;
647 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
648 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
649 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
651 tmp->makeDocBookFile(writefile, runparams, true);
654 runparams.exportdata->addExternalFile("docbook", writefile,
655 exportfile);
656 runparams.exportdata->addExternalFile("docbook-xml", writefile,
657 exportfile);
659 if (isVerbatim(params_) || isListings(params_)) {
660 os << "<inlinegraphic fileref=\""
661 << '&' << include_label << ';'
662 << "\" format=\"linespecific\">";
663 } else
664 os << '&' << include_label << ';';
666 return 0;
670 void InsetInclude::validate(LaTeXFeatures & features) const
672 string incfile(to_utf8(params_["filename"]));
673 string writefile;
675 Buffer const & buffer = features.buffer();
677 string const included_file = includedFilename(buffer, params_).absFilename();
679 if (isLyXFilename(included_file))
680 writefile = changeExtension(included_file, ".sgml");
681 else
682 writefile = included_file;
684 if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
685 incfile = DocFileName(writefile).mangledFilename();
686 writefile = makeAbsPath(incfile,
687 buffer.getMasterBuffer()->temppath()).absFilename();
690 features.includeFile(include_label, writefile);
692 if (isVerbatim(params_))
693 features.require("verbatim");
694 else if (isListings(params_))
695 features.require("listings");
697 // Here we must do the fun stuff...
698 // Load the file in the include if it needs
699 // to be loaded:
700 if (loadIfNeeded(buffer, params_)) {
701 // a file got loaded
702 Buffer * const tmp = theBufferList().getBuffer(included_file);
703 // make sure the buffer isn't us
704 // FIXME RECURSIVE INCLUDES
705 // This is not sufficient, as recursive includes could be
706 // more than a file away. But it will do for now.
707 if (tmp && tmp != & buffer) {
708 // We must temporarily change features.buffer,
709 // otherwise it would always be the master buffer,
710 // and nested includes would not work.
711 features.setBuffer(*tmp);
712 tmp->validate(features);
713 features.setBuffer(buffer);
719 void InsetInclude::getLabelList(Buffer const & buffer,
720 std::vector<docstring> & list) const
722 if (isListings(params_)) {
723 InsetListingsParams params(params_.getOptions());
724 string label = params.getParamValue("label");
725 if (!label.empty())
726 list.push_back(from_utf8(label));
728 else if (loadIfNeeded(buffer, params_)) {
729 string const included_file = includedFilename(buffer, params_).absFilename();
730 Buffer * tmp = theBufferList().getBuffer(included_file);
731 tmp->setParentName("");
732 tmp->getLabelList(list);
733 tmp->setParentName(parentFilename(buffer));
738 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
739 std::vector<std::pair<string, docstring> > & keys) const
741 if (loadIfNeeded(buffer, params_)) {
742 string const included_file = includedFilename(buffer, params_).absFilename();
743 Buffer * tmp = theBufferList().getBuffer(included_file);
744 tmp->setParentName("");
745 tmp->fillWithBibKeys(keys);
746 tmp->setParentName(parentFilename(buffer));
751 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
753 Buffer * const tmp = getChildBuffer(buffer, params_);
754 if (tmp) {
755 tmp->setParentName("");
756 tmp->updateBibfilesCache();
757 tmp->setParentName(parentFilename(buffer));
762 std::vector<FileName> const &
763 InsetInclude::getBibfilesCache(Buffer const & buffer) const
765 Buffer * const tmp = getChildBuffer(buffer, params_);
766 if (tmp) {
767 tmp->setParentName("");
768 std::vector<FileName> const & cache = tmp->getBibfilesCache();
769 tmp->setParentName(parentFilename(buffer));
770 return cache;
772 static std::vector<FileName> const empty;
773 return empty;
777 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
779 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
781 bool use_preview = false;
782 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
783 graphics::PreviewImage const * pimage =
784 preview_->getPreviewImage(*mi.base.bv->buffer());
785 use_preview = pimage && pimage->image();
788 if (use_preview) {
789 preview_->metrics(mi, dim);
790 } else {
791 if (!set_label_) {
792 set_label_ = true;
793 button_.update(getScreenLabel(*mi.base.bv->buffer()),
794 true);
796 button_.metrics(mi, dim);
799 Box b(0, dim.wid, -dim.asc, dim.des);
800 button_.setBox(b);
802 bool const changed = dim_ != dim;
803 dim_ = dim;
804 return changed;
808 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
810 setPosCache(pi, x, y);
812 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
814 bool use_preview = false;
815 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
816 graphics::PreviewImage const * pimage =
817 preview_->getPreviewImage(*pi.base.bv->buffer());
818 use_preview = pimage && pimage->image();
821 if (use_preview)
822 preview_->draw(pi, x, y);
823 else
824 button_.draw(pi, x, y);
828 Inset::DisplayType InsetInclude::display() const
830 return type(params_) == INPUT ? Inline : AlignCenter;
836 // preview stuff
839 void InsetInclude::fileChanged() const
841 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
842 if (!buffer_ptr)
843 return;
845 Buffer const & buffer = *buffer_ptr;
846 preview_->removePreview(buffer);
847 add_preview(*preview_.get(), *this, buffer);
848 preview_->startLoading(buffer);
852 namespace {
854 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
856 FileName const included_file = includedFilename(buffer, params);
858 return type(params) == INPUT && params.preview() &&
859 isFileReadable(included_file);
863 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
865 odocstringstream os;
866 // We don't need to set runparams.encoding since this will be done
867 // by latex() anyway.
868 OutputParams runparams(0);
869 runparams.flavor = OutputParams::LATEX;
870 inset.latex(buffer, os, runparams);
872 return os.str();
876 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
877 Buffer const & buffer)
879 InsetCommandParams const & params = inset.params();
880 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
881 preview_wanted(params, buffer)) {
882 renderer.setAbsFile(includedFilename(buffer, params));
883 docstring const snippet = latex_string(inset, buffer);
884 renderer.addPreview(snippet, buffer);
888 } // namespace anon
891 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
893 Buffer const & buffer = ploader.buffer();
894 if (preview_wanted(params(), buffer)) {
895 preview_->setAbsFile(includedFilename(buffer, params()));
896 docstring const snippet = latex_string(*this, buffer);
897 preview_->addPreview(snippet, ploader);
902 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer, ParConstIterator const & pit) const
904 if (isListings(params_)) {
905 InsetListingsParams params(params_.getOptions());
906 string caption = params.getParamValue("caption");
907 if (!caption.empty()) {
908 Toc & toc = toclist["listing"];
909 docstring const str = convert<docstring>(toc.size() + 1)
910 + ". " + from_utf8(caption);
911 // This inset does not have a valid ParConstIterator
912 // so it has to use the iterator of its parent paragraph
913 toc.push_back(TocItem(pit, 0, str));
915 return;
917 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
918 if (!childbuffer)
919 return;
921 TocList const & childtoclist = childbuffer->tocBackend().tocs();
922 TocList::const_iterator it = childtoclist.begin();
923 TocList::const_iterator const end = childtoclist.end();
924 for(; it != end; ++it)
925 toclist[it->first].insert(toclist[it->first].end(),
926 it->second.begin(), it->second.end());
930 void InsetInclude::updateLabels(Buffer const & buffer) const
932 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
933 if (!childbuffer)
934 return;
936 lyx::updateLabels(*childbuffer, true);
940 void InsetInclude::updateCounter(Counters & counters)
942 if (!isListings(params_))
943 return;
945 InsetListingsParams const par = params_.getOptions();
946 if (par.getParamValue("caption").empty())
947 counter_ = 0;
948 else {
949 counters.step(from_ascii("listing"));
950 counter_ = counters.value(from_ascii("listing"));
955 string const InsetIncludeMailer::name_("include");
957 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
958 : inset_(inset)
962 string const InsetIncludeMailer::inset2string(Buffer const &) const
964 return params2string(inset_.params());
968 void InsetIncludeMailer::string2params(string const & in,
969 InsetCommandParams & params)
971 params.clear();
972 if (in.empty())
973 return;
975 istringstream data(in);
976 Lexer lex(0,0);
977 lex.setStream(data);
979 string name;
980 lex >> name;
981 if (!lex || name != name_)
982 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
984 // This is part of the inset proper that is usually swallowed
985 // by Text::readInset
986 string id;
987 lex >> id;
988 if (!lex || id != "Include")
989 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
991 InsetInclude inset(params);
992 inset.read(lex);
993 params = inset.params();
997 string const
998 InsetIncludeMailer::params2string(InsetCommandParams const & params)
1000 InsetInclude inset(params);
1001 ostringstream data;
1002 data << name_ << ' ';
1003 inset.write(data);
1004 data << "\\end_inset\n";
1005 return data.str();
1009 } // namespace lyx