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.
13 #include "InsetInclude.h"
16 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
22 #include "DispatchResult.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
27 #include "LaTeXFeatures.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>
56 using support::addName;
57 using support::absolutePath;
58 using support::bformat;
59 using support::changeExtension;
60 using support::contains;
62 using support::DocFileName;
63 using support::FileName;
64 using support::getFileContents;
65 using support::getVectorFromString;
66 using support::isFileReadable;
67 using support::isLyXFilename;
68 using support::latex_path;
69 using support::makeAbsPath;
70 using support::makeDisplayPath;
71 using support::makeRelPath;
72 using support::onlyFilename;
73 using support::onlyPath;
74 using support::prefixIs;
81 using std::istringstream;
83 using std::ostringstream;
86 namespace Alert = frontend::Alert;
87 namespace fs = boost::filesystem;
92 docstring const uniqueID()
94 static unsigned int seed = 1000;
95 return "file" + convert<docstring>(++seed);
99 bool isListings(InsetCommandParams const & params)
101 return params.getCmdName() == "lstinputlisting";
107 InsetInclude::InsetInclude(InsetCommandParams const & p)
108 : params_(p), include_label(uniqueID()),
109 preview_(new RenderMonitoredPreview(this)),
110 set_label_(false), counter_(0)
112 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
116 InsetInclude::InsetInclude(InsetInclude const & other)
118 params_(other.params_),
119 include_label(other.include_label),
120 preview_(new RenderMonitoredPreview(this)),
121 set_label_(false), counter_(0)
123 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
127 InsetInclude::~InsetInclude()
129 InsetIncludeMailer(*this).hideDialog();
133 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
135 switch (cmd.action) {
137 case LFUN_INSET_MODIFY: {
138 InsetCommandParams p("include");
139 InsetIncludeMailer::string2params(to_utf8(cmd.argument()), p);
140 if (!p.getCmdName().empty()) {
142 InsetListingsParams par_old(params().getOptions());
143 InsetListingsParams par_new(p.getOptions());
144 if (par_old.getParamValue("label") !=
145 par_new.getParamValue("label")
146 && !par_new.getParamValue("label").empty())
147 cur.bv().buffer()->changeRefsIfUnique(
148 from_utf8(par_old.getParamValue("label")),
149 from_utf8(par_new.getParamValue("label")),
152 set(p, cur.buffer());
153 cur.buffer().updateBibfilesCache();
159 case LFUN_INSET_DIALOG_UPDATE:
160 InsetIncludeMailer(*this).updateDialog(&cur.bv());
163 case LFUN_MOUSE_RELEASE:
164 if (!cur.selection())
165 InsetIncludeMailer(*this).showDialog(&cur.bv());
169 Inset::doDispatch(cur, cmd);
175 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
176 FuncStatus & flag) const
178 switch (cmd.action) {
180 case LFUN_INSET_MODIFY:
181 case LFUN_INSET_DIALOG_UPDATE:
186 return Inset::getStatus(cur, cmd, flag);
191 InsetCommandParams const & InsetInclude::params() const
199 /// the type of inclusion
209 Types type(InsetCommandParams const & params)
211 string const command_name = params.getCmdName();
213 if (command_name == "input")
215 if (command_name == "verbatiminput")
217 if (command_name == "verbatiminput*")
219 if (command_name == "lstinputlisting")
225 bool isVerbatim(InsetCommandParams const & params)
227 string const command_name = params.getCmdName();
228 return command_name == "verbatiminput" ||
229 command_name == "verbatiminput*";
233 bool isInputOrInclude(InsetCommandParams const & params)
235 Types const t = type(params);
236 return (t == INPUT) || (t == INCLUDE);
240 string const masterFilename(Buffer const & buffer)
242 return buffer.getMasterBuffer()->fileName();
246 string const parentFilename(Buffer const & buffer)
248 return buffer.fileName();
252 FileName const includedFilename(Buffer const & buffer,
253 InsetCommandParams const & params)
255 return makeAbsPath(to_utf8(params["filename"]),
256 onlyPath(parentFilename(buffer)));
260 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
265 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
270 if (preview_->monitoring())
271 preview_->stopMonitoring();
273 if (type(params_) == INPUT)
274 add_preview(*preview_, *this, buffer);
278 auto_ptr<Inset> InsetInclude::doClone() const
280 return auto_ptr<Inset>(new InsetInclude(*this));
284 void InsetInclude::write(Buffer const &, ostream & os) const
290 void InsetInclude::write(ostream & os) const
292 os << "Include " << to_utf8(params_.getCommand()) << '\n'
293 << "preview " << convert<string>(params_.preview()) << '\n';
297 void InsetInclude::read(Buffer const &, Lexer & lex)
303 void InsetInclude::read(Lexer & lex)
307 string const command = lex.getString();
308 params_.scanCommand(command);
313 token = lex.getString();
314 if (token == "\\end_inset")
316 if (token == "preview") {
318 params_.preview(lex.getBool());
320 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
322 if (token != "\\end_inset") {
323 lex.printError("Missing \\end_inset at this point. "
329 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
333 switch (type(params_)) {
335 temp += buf.B_("Input");
338 temp += buf.B_("Verbatim Input");
341 temp += buf.B_("Verbatim Input*");
344 temp += buf.B_("Include");
348 temp += buf.B_("Program Listing ") + convert<docstring>(counter_);
350 temp += buf.B_("Program Listing");
357 if (params_["filename"].empty())
360 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
368 /// return the child buffer if the file is a LyX doc and is loaded
369 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
371 if (isVerbatim(params) || isListings(params))
374 string const included_file = includedFilename(buffer, params).absFilename();
375 if (!isLyXFilename(included_file))
378 Buffer * childBuffer = theBufferList().getBuffer(included_file);
380 //FIXME RECURSIVE INCLUDES
381 if (childBuffer == & buffer)
388 /// return true if the file is or got loaded.
389 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
391 if (isVerbatim(params) || isListings(params))
394 FileName const included_file = includedFilename(buffer, params);
395 if (!isLyXFilename(included_file.absFilename()))
398 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
400 // the readonly flag can/will be wrong, not anymore I think.
401 if (!fs::exists(included_file.toFilesystemEncoding()))
403 buf = theBufferList().newBuffer(included_file.absFilename());
404 if (!loadLyXFile(buf, included_file)) {
405 //close the buffer we just opened
406 theBufferList().close(buf, false);
410 buf->setParentName(parentFilename(buffer));
418 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
419 OutputParams const & runparams) const
421 string incfile(to_utf8(params_["filename"]));
423 // Do nothing if no file name has been specified
427 FileName const included_file(includedFilename(buffer, params_));
429 //Check we're not trying to include ourselves.
430 //FIXME RECURSIVE INCLUDE
431 //This isn't sufficient, as the inclusion could be downstream.
432 //But it'll have to do for now.
433 if (isInputOrInclude(params_) &&
434 buffer.fileName() == included_file.toFilesystemEncoding())
436 Alert::error(_("Recursive input"),
437 bformat(_("Attempted to include file %1$s in itself! "
438 "Ignoring inclusion."), from_utf8(incfile)));
442 Buffer const * const m_buffer = buffer.getMasterBuffer();
444 // if incfile is relative, make it relative to the master
446 if (!absolutePath(incfile)) {
448 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
449 from_utf8(m_buffer->filePath())));
452 // write it to a file (so far the complete file)
453 string const exportfile = changeExtension(incfile, ".tex");
454 string const mangled =
455 DocFileName(changeExtension(included_file.absFilename(),".tex")).
457 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
461 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
462 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
463 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
465 if (runparams.inComment || runparams.dryrun)
466 // Don't try to load or copy the file
468 //if it's a LyX file and we're including or inputting it...
469 else if (isInputOrInclude(params_) &&
470 isLyXFilename(included_file.absFilename())) {
471 //try to load it so we can write the associated latex
472 if (!loadIfNeeded(buffer, params_))
475 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
477 if (tmp->params().textclass != m_buffer->params().textclass) {
479 docstring text = bformat(_("Included file `%1$s'\n"
480 "has textclass `%2$s'\n"
481 "while parent file has textclass `%3$s'."),
482 makeDisplayPath(included_file.absFilename()),
483 from_utf8(tmp->params().getTextClass().name()),
484 from_utf8(m_buffer->params().getTextClass().name()));
485 Alert::warning(_("Different textclasses"), text);
489 tmp->markDepClean(m_buffer->temppath());
492 #warning handle non existing files
493 #warning Second argument is irrelevant!
494 // since only_body is true, makeLaTeXFile will not look at second
495 // argument. Should we set it to string(), or should makeLaTeXFile
496 // make use of it somehow? (JMarc 20031002)
498 // The included file might be written in a different encoding
499 Encoding const * const oldEnc = runparams.encoding;
500 runparams.encoding = &tmp->params().encoding();
501 tmp->makeLaTeXFile(writefile,
502 onlyPath(masterFilename(buffer)),
504 runparams.encoding = oldEnc;
506 // Copy the file to the temp dir, so that .aux files etc.
507 // are not created in the original dir. Files included by
508 // this file will be found via input@path, see ../Buffer.cpp.
509 unsigned long const checksum_in = sum(included_file);
510 unsigned long const checksum_out = sum(writefile);
512 if (checksum_in != checksum_out) {
513 if (!copy(included_file, writefile)) {
516 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
517 "into the temporary directory."),
518 from_utf8(included_file.absFilename())))
525 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
526 "latex" : "pdflatex";
527 if (isVerbatim(params_)) {
528 incfile = latex_path(incfile);
530 os << '\\' << from_ascii(params_.getCmdName()) << '{'
531 << from_utf8(incfile) << '}';
532 } else if (type(params_) == INPUT) {
533 runparams.exportdata->addExternalFile(tex_format, writefile,
536 // \input wants file with extension (default is .tex)
537 if (!isLyXFilename(included_file.absFilename())) {
538 incfile = latex_path(incfile);
540 os << '\\' << from_ascii(params_.getCmdName())
541 << '{' << from_utf8(incfile) << '}';
543 incfile = changeExtension(incfile, ".tex");
544 incfile = latex_path(incfile);
546 os << '\\' << from_ascii(params_.getCmdName())
547 << '{' << from_utf8(incfile) << '}';
549 } else if (type(params_) == LISTINGS) {
550 os << '\\' << from_ascii(params_.getCmdName());
551 string opt = params_.getOptions();
552 // opt is set in QInclude dialog and should have passed validation.
553 InsetListingsParams params(opt);
554 if (!params.params().empty())
555 os << "[" << from_utf8(params.params()) << "]";
556 os << '{' << from_utf8(incfile) << '}';
558 runparams.exportdata->addExternalFile(tex_format, writefile,
561 // \include don't want extension and demands that the
562 // file really have .tex
563 incfile = changeExtension(incfile, string());
564 incfile = latex_path(incfile);
566 os << '\\' << from_ascii(params_.getCmdName()) << '{'
567 << from_utf8(incfile) << '}';
574 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
575 OutputParams const &) const
577 if (isVerbatim(params_) || isListings(params_)) {
578 os << '[' << getScreenLabel(buffer) << '\n';
579 // FIXME: We don't know the encoding of the file
580 docstring const str =
581 from_utf8(getFileContents(includedFilename(buffer, params_)));
584 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
586 docstring const str = '[' + getScreenLabel(buffer) + ']';
593 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
594 OutputParams const & runparams) const
596 string incfile = to_utf8(params_["filename"]);
598 // Do nothing if no file name has been specified
602 string const included_file = includedFilename(buffer, params_).absFilename();
604 //Check we're not trying to include ourselves.
605 //FIXME RECURSIVE INCLUDE
606 //This isn't sufficient, as the inclusion could be downstream.
607 //But it'll have to do for now.
608 if (buffer.fileName() == included_file) {
609 Alert::error(_("Recursive input"),
610 bformat(_("Attempted to include file %1$s in itself! "
611 "Ignoring inclusion."), from_utf8(incfile)));
615 // write it to a file (so far the complete file)
616 string const exportfile = changeExtension(incfile, ".sgml");
617 DocFileName writefile(changeExtension(included_file, ".sgml"));
619 if (loadIfNeeded(buffer, params_)) {
620 Buffer * tmp = theBufferList().getBuffer(included_file);
622 string const mangled = writefile.mangledFilename();
623 writefile = makeAbsPath(mangled,
624 buffer.getMasterBuffer()->temppath());
628 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
629 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
630 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
632 tmp->makeDocBookFile(writefile, runparams, true);
635 runparams.exportdata->addExternalFile("docbook", writefile,
637 runparams.exportdata->addExternalFile("docbook-xml", writefile,
640 if (isVerbatim(params_) || isListings(params_)) {
641 os << "<inlinegraphic fileref=\""
642 << '&' << include_label << ';'
643 << "\" format=\"linespecific\">";
645 os << '&' << include_label << ';';
651 void InsetInclude::validate(LaTeXFeatures & features) const
653 string incfile(to_utf8(params_["filename"]));
656 Buffer const & buffer = features.buffer();
658 string const included_file = includedFilename(buffer, params_).absFilename();
660 if (isLyXFilename(included_file))
661 writefile = changeExtension(included_file, ".sgml");
663 writefile = included_file;
665 if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
666 incfile = DocFileName(writefile).mangledFilename();
667 writefile = makeAbsPath(incfile,
668 buffer.getMasterBuffer()->temppath()).absFilename();
671 features.includeFile(include_label, writefile);
673 if (isVerbatim(params_))
674 features.require("verbatim");
675 else if (isListings(params_))
676 features.require("listings");
678 // Here we must do the fun stuff...
679 // Load the file in the include if it needs
681 if (loadIfNeeded(buffer, params_)) {
683 Buffer * const tmp = theBufferList().getBuffer(included_file);
684 // make sure the buffer isn't us
685 // FIXME RECURSIVE INCLUDES
686 // This is not sufficient, as recursive includes could be
687 // more than a file away. But it will do for now.
688 if (tmp && tmp != & buffer) {
689 // We must temporarily change features.buffer,
690 // otherwise it would always be the master buffer,
691 // and nested includes would not work.
692 features.setBuffer(*tmp);
693 tmp->validate(features);
694 features.setBuffer(buffer);
700 void InsetInclude::getLabelList(Buffer const & buffer,
701 std::vector<docstring> & list) const
703 if (isListings(params_)) {
704 InsetListingsParams params(params_.getOptions());
705 string label = params.getParamValue("label");
707 list.push_back(from_utf8(label));
709 else if (loadIfNeeded(buffer, params_)) {
710 string const included_file = includedFilename(buffer, params_).absFilename();
711 Buffer * tmp = theBufferList().getBuffer(included_file);
712 tmp->setParentName("");
713 tmp->getLabelList(list);
714 tmp->setParentName(parentFilename(buffer));
719 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
720 std::vector<std::pair<string, docstring> > & keys) const
722 if (loadIfNeeded(buffer, params_)) {
723 string const included_file = includedFilename(buffer, params_).absFilename();
724 Buffer * tmp = theBufferList().getBuffer(included_file);
725 tmp->setParentName("");
726 tmp->fillWithBibKeys(keys);
727 tmp->setParentName(parentFilename(buffer));
732 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
734 Buffer * const tmp = getChildBuffer(buffer, params_);
736 tmp->setParentName("");
737 tmp->updateBibfilesCache();
738 tmp->setParentName(parentFilename(buffer));
743 std::vector<FileName> const &
744 InsetInclude::getBibfilesCache(Buffer const & buffer) const
746 Buffer * const tmp = getChildBuffer(buffer, params_);
748 tmp->setParentName("");
749 std::vector<FileName> const & cache = tmp->getBibfilesCache();
750 tmp->setParentName(parentFilename(buffer));
753 static std::vector<FileName> const empty;
758 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
760 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
762 bool use_preview = false;
763 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
764 graphics::PreviewImage const * pimage =
765 preview_->getPreviewImage(*mi.base.bv->buffer());
766 use_preview = pimage && pimage->image();
770 preview_->metrics(mi, dim);
774 button_.update(getScreenLabel(*mi.base.bv->buffer()),
777 button_.metrics(mi, dim);
780 Box b(0, dim.wid, -dim.asc, dim.des);
783 bool const changed = dim_ != dim;
789 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
791 setPosCache(pi, x, y);
793 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
795 bool use_preview = false;
796 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
797 graphics::PreviewImage const * pimage =
798 preview_->getPreviewImage(*pi.base.bv->buffer());
799 use_preview = pimage && pimage->image();
803 preview_->draw(pi, x, y);
805 button_.draw(pi, x, y);
809 Inset::DisplayType InsetInclude::display() const
811 return type(params_) == INPUT ? Inline : AlignCenter;
820 void InsetInclude::fileChanged() const
822 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
826 Buffer const & buffer = *buffer_ptr;
827 preview_->removePreview(buffer);
828 add_preview(*preview_.get(), *this, buffer);
829 preview_->startLoading(buffer);
835 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
837 FileName const included_file = includedFilename(buffer, params);
839 return type(params) == INPUT && params.preview() &&
840 isFileReadable(included_file);
844 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
847 // We don't need to set runparams.encoding since this will be done
848 // by latex() anyway.
849 OutputParams runparams(0);
850 runparams.flavor = OutputParams::LATEX;
851 inset.latex(buffer, os, runparams);
857 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
858 Buffer const & buffer)
860 InsetCommandParams const & params = inset.params();
861 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
862 preview_wanted(params, buffer)) {
863 renderer.setAbsFile(includedFilename(buffer, params));
864 docstring const snippet = latex_string(inset, buffer);
865 renderer.addPreview(snippet, buffer);
872 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
874 Buffer const & buffer = ploader.buffer();
875 if (preview_wanted(params(), buffer)) {
876 preview_->setAbsFile(includedFilename(buffer, params()));
877 docstring const snippet = latex_string(*this, buffer);
878 preview_->addPreview(snippet, ploader);
883 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
885 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
889 TocList const & childtoclist = childbuffer->tocBackend().tocs();
890 TocList::const_iterator it = childtoclist.begin();
891 TocList::const_iterator const end = childtoclist.end();
892 for(; it != end; ++it)
893 toclist[it->first].insert(toclist[it->first].end(),
894 it->second.begin(), it->second.end());
898 void InsetInclude::updateLabels(Buffer const & buffer) const
900 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
904 lyx::updateLabels(*childbuffer, true);
908 void InsetInclude::updateCounter(Counters & counters)
910 if (!isListings(params_))
913 InsetListingsParams const par = params_.getOptions();
914 if (par.getParamValue("caption").empty())
917 counters.step(from_ascii("listing"));
918 counter_ = counters.value(from_ascii("listing"));
923 string const InsetIncludeMailer::name_("include");
925 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
930 string const InsetIncludeMailer::inset2string(Buffer const &) const
932 return params2string(inset_.params());
936 void InsetIncludeMailer::string2params(string const & in,
937 InsetCommandParams & params)
943 istringstream data(in);
949 if (!lex || name != name_)
950 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
952 // This is part of the inset proper that is usually swallowed
953 // by Text::readInset
956 if (!lex || id != "Include")
957 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
959 InsetInclude inset(params);
961 params = inset.params();
966 InsetIncludeMailer::params2string(InsetCommandParams const & params)
968 InsetInclude inset(params);
970 data << name_ << ' ';
972 data << "\\end_inset\n";