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
7 * \author Richard Heck (conversion to InsetCommand)
9 * Full author contact details are available in file CREDITS.
14 #include "InsetInclude.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
22 #include "DispatchResult.h"
23 #include "ErrorList.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "LayoutFile.h"
34 #include "MetricsInfo.h"
35 #include "OutputParams.h"
36 #include "TextClass.h"
37 #include "TocBackend.h"
39 #include "frontends/alert.h"
40 #include "frontends/Painter.h"
42 #include "graphics/PreviewImage.h"
43 #include "graphics/PreviewLoader.h"
45 #include "insets/InsetLabel.h"
46 #include "insets/InsetListingsParams.h"
47 #include "insets/RenderPreview.h"
49 #include "support/convert.h"
50 #include "support/debug.h"
51 #include "support/docstream.h"
52 #include "support/FileNameList.h"
53 #include "support/filetools.h"
54 #include "support/gettext.h"
55 #include "support/lassert.h"
56 #include "support/lstrings.h" // contains
57 #include "support/lyxalgo.h"
59 #include <boost/bind.hpp>
62 using namespace lyx::support;
66 namespace Alert = frontend::Alert;
71 docstring const uniqueID()
73 static unsigned int seed = 1000;
74 return "file" + convert<docstring>(++seed);
78 /// the type of inclusion
80 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
84 Types type(string const & s)
88 if (s == "verbatiminput")
90 if (s == "verbatiminput*")
92 if (s == "lstinputlisting")
100 Types type(InsetCommandParams const & params)
102 return type(params.getCmdName());
106 bool isListings(InsetCommandParams const & params)
108 return type(params) == LISTINGS;
112 bool isVerbatim(InsetCommandParams const & params)
114 Types const t = type(params);
115 return t == VERB || t == VERBAST;
119 bool isInputOrInclude(InsetCommandParams const & params)
121 Types const t = type(params);
122 return t == INPUT || t == INCLUDE;
126 FileName const masterFileName(Buffer const & buffer)
128 return buffer.masterBuffer()->fileName();
132 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
135 string const parentFilename(Buffer const & buffer)
137 return buffer.absFileName();
141 FileName const includedFilename(Buffer const & buffer,
142 InsetCommandParams const & params)
144 return makeAbsPath(to_utf8(params["filename"]),
145 onlyPath(parentFilename(buffer)));
149 InsetLabel * createLabel(docstring const & label_str)
151 if (label_str.empty())
153 InsetCommandParams icp(LABEL_CODE);
154 icp["name"] = label_str;
155 return new InsetLabel(icp);
161 InsetInclude::InsetInclude(InsetCommandParams const & p)
162 : InsetCommand(p, "include"), include_label(uniqueID()),
163 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
165 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
167 if (isListings(params())) {
168 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
169 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
174 InsetInclude::InsetInclude(InsetInclude const & other)
175 : InsetCommand(other), include_label(other.include_label),
176 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
178 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
181 label_ = new InsetLabel(*other.label_);
185 InsetInclude::~InsetInclude()
191 void InsetInclude::setBuffer(Buffer & buffer)
193 InsetCommand::setBuffer(buffer);
195 label_->setBuffer(buffer);
199 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
202 // This is only correct for the case of listings, but it'll do for now.
203 // In the other cases, this second parameter should just be empty.
204 static ParamInfo param_info_;
205 if (param_info_.empty()) {
206 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
207 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
213 bool InsetInclude::isCompatibleCommand(string const & s)
215 return type(s) != NONE;
219 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
221 LASSERT(cur.buffer() == &buffer(), return);
222 switch (cmd.action) {
224 case LFUN_INSET_EDIT: {
225 editIncluded(to_utf8(params()["filename"]));
229 case LFUN_INSET_MODIFY: {
230 InsetCommandParams p(INCLUDE_CODE);
231 if (cmd.getArg(0) == "changetype") {
232 InsetCommand::doDispatch(cur, cmd);
235 InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
236 if (!p.getCmdName().empty()) {
238 InsetListingsParams new_params(to_utf8(p["lstparams"]));
239 docstring const new_label =
240 from_utf8(new_params.getParamValue("label"));
243 old_label = label_->getParam("name");
244 if (new_label.empty())
246 else if (label_ && old_label != new_label) {
247 label_->updateCommand(new_label);
248 // the label might have been adapted (duplicate)
249 if (new_label != label_->getParam("name")) {
250 new_params.addParam("label",
251 "{" + to_utf8(label_->getParam("name")) + "}");
252 p["lstparams"] = from_utf8(new_params.params());
254 } else if (old_label != new_label) {
255 label_ = createLabel(new_label);
256 label_->setBuffer(buffer());
266 //pass everything else up the chain
268 InsetCommand::doDispatch(cur, cmd);
274 void InsetInclude::editIncluded(string const & file)
276 string const ext = support::getExtension(file);
278 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
281 // tex file or other text file in verbatim mode
282 formats.edit(buffer(),
283 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
288 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
289 FuncStatus & flag) const
291 switch (cmd.action) {
293 case LFUN_INSET_EDIT:
294 case LFUN_INSET_MODIFY:
295 flag.setEnabled(true);
299 return InsetCommand::getStatus(cur, cmd, flag);
304 void InsetInclude::setParams(InsetCommandParams const & p)
306 InsetCommand::setParams(p);
309 if (preview_->monitoring())
310 preview_->stopMonitoring();
312 if (type(params()) == INPUT)
313 add_preview(*preview_, *this, buffer());
315 buffer().updateBibfilesCache();
319 docstring InsetInclude::screenLabel() const
323 switch (type(params())) {
325 temp = buffer().B_("Input");
328 temp = buffer().B_("Verbatim Input");
331 temp = buffer().B_("Verbatim Input*");
334 temp = buffer().B_("Include");
337 temp = listings_label_;
340 LASSERT(false, /**/);
345 if (params()["filename"].empty())
348 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
354 /// return the child buffer if the file is a LyX doc and is loaded
355 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
357 if (isVerbatim(params) || isListings(params))
360 string const included_file = includedFilename(buffer, params).absFilename();
361 if (!isLyXFilename(included_file))
364 Buffer * childBuffer = loadIfNeeded(buffer, params);
366 // FIXME: recursive includes
367 return (childBuffer == &buffer) ? 0 : childBuffer;
371 /// return true if the file is or got loaded.
372 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
374 if (isVerbatim(params) || isListings(params))
377 string const parent_filename = parent.absFileName();
378 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
379 onlyPath(parent_filename));
381 if (!isLyXFilename(included_file.absFilename()))
384 Buffer * child = theBufferList().getBuffer(included_file);
386 // the readonly flag can/will be wrong, not anymore I think.
387 if (!included_file.exists())
390 child = theBufferList().newBuffer(included_file.absFilename());
392 // Buffer creation is not possible.
395 if (!child->loadLyXFile(included_file)) {
396 //close the buffer we just opened
397 theBufferList().release(child);
401 if (!child->errorList("Parse").empty()) {
402 // FIXME: Do something.
405 child->setParent(&parent);
410 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
412 string incfile = to_utf8(params()["filename"]);
414 // Do nothing if no file name has been specified
418 FileName const included_file = includedFilename(buffer(), params());
420 // Check we're not trying to include ourselves.
421 // FIXME RECURSIVE INCLUDE
422 // This isn't sufficient, as the inclusion could be downstream.
423 // But it'll have to do for now.
424 if (isInputOrInclude(params()) &&
425 buffer().absFileName() == included_file.absFilename())
427 Alert::error(_("Recursive input"),
428 bformat(_("Attempted to include file %1$s in itself! "
429 "Ignoring inclusion."), from_utf8(incfile)));
433 Buffer const * const masterBuffer = buffer().masterBuffer();
435 // if incfile is relative, make it relative to the master
437 if (!FileName(incfile).isAbsolute()) {
439 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
440 from_utf8(masterBuffer->filePath())));
443 // write it to a file (so far the complete file)
444 string const exportfile = changeExtension(incfile, ".tex");
445 string const mangled =
446 DocFileName(changeExtension(included_file.absFilename(),".tex")).
448 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
452 else if (!isValidLaTeXFilename(incfile)) {
453 frontend::Alert::warning(_("Invalid filename"),
454 _("The following filename is likely to cause trouble "
455 "when running the exported file through LaTeX: ") +
458 LYXERR(Debug::LATEX, "incfile:" << incfile);
459 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
460 LYXERR(Debug::LATEX, "writefile:" << writefile);
462 if (runparams.inComment || runparams.dryrun) {
463 //Don't try to load or copy the file if we're
464 //in a comment or doing a dryrun
465 } else if (isInputOrInclude(params()) &&
466 isLyXFilename(included_file.absFilename())) {
467 //if it's a LyX file and we're inputting or including,
468 //try to load it so we can write the associated latex
469 if (!loadIfNeeded(buffer(), params()))
472 Buffer * tmp = theBufferList().getBuffer(included_file);
474 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
476 docstring text = bformat(_("Included file `%1$s'\n"
477 "has textclass `%2$s'\n"
478 "while parent file has textclass `%3$s'."),
479 included_file.displayName(),
480 from_utf8(tmp->params().documentClass().name()),
481 from_utf8(masterBuffer->params().documentClass().name()));
482 Alert::warning(_("Different textclasses"), text);
485 // Make sure modules used in child are all included in master
486 //FIXME It might be worth loading the children's modules into the master
487 //over in BufferParams rather than doing this check.
488 list<string> const masterModules = masterBuffer->params().getModules();
489 list<string> const childModules = tmp->params().getModules();
490 list<string>::const_iterator it = childModules.begin();
491 list<string>::const_iterator end = childModules.end();
492 for (; it != end; ++it) {
493 string const module = *it;
494 list<string>::const_iterator found =
495 find(masterModules.begin(), masterModules.end(), module);
496 if (found == masterModules.end()) {
497 docstring text = bformat(_("Included file `%1$s'\n"
498 "uses module `%2$s'\n"
499 "which is not used in parent file."),
500 included_file.displayName(), from_utf8(module));
501 Alert::warning(_("Module not found"), text);
505 tmp->markDepClean(masterBuffer->temppath());
507 // FIXME: handle non existing files
508 // FIXME: Second argument is irrelevant!
509 // since only_body is true, makeLaTeXFile will not look at second
510 // argument. Should we set it to string(), or should makeLaTeXFile
511 // make use of it somehow? (JMarc 20031002)
512 // The included file might be written in a different encoding
513 Encoding const * const oldEnc = runparams.encoding;
514 runparams.encoding = &tmp->params().encoding();
515 tmp->makeLaTeXFile(writefile,
516 masterFileName(buffer()).onlyPath().absFilename(),
518 runparams.encoding = oldEnc;
520 // In this case, it's not a LyX file, so we copy the file
521 // to the temp dir, so that .aux files etc. are not created
522 // in the original dir. Files included by this file will be
523 // found via input@path, see ../Buffer.cpp.
524 unsigned long const checksum_in = included_file.checksum();
525 unsigned long const checksum_out = writefile.checksum();
527 if (checksum_in != checksum_out) {
528 if (!included_file.copyTo(writefile)) {
531 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
532 "into the temporary directory."),
533 from_utf8(included_file.absFilename()))));
539 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
540 "latex" : "pdflatex";
541 if (isVerbatim(params())) {
542 incfile = latex_path(incfile);
544 os << '\\' << from_ascii(params().getCmdName()) << '{'
545 << from_utf8(incfile) << '}';
546 } else if (type(params()) == INPUT) {
547 runparams.exportdata->addExternalFile(tex_format, writefile,
550 // \input wants file with extension (default is .tex)
551 if (!isLyXFilename(included_file.absFilename())) {
552 incfile = latex_path(incfile);
554 os << '\\' << from_ascii(params().getCmdName())
555 << '{' << from_utf8(incfile) << '}';
557 incfile = changeExtension(incfile, ".tex");
558 incfile = latex_path(incfile);
560 os << '\\' << from_ascii(params().getCmdName())
561 << '{' << from_utf8(incfile) << '}';
563 } else if (type(params()) == LISTINGS) {
564 os << '\\' << from_ascii(params().getCmdName());
565 string const opt = to_utf8(params()["lstparams"]);
566 // opt is set in QInclude dialog and should have passed validation.
567 InsetListingsParams params(opt);
568 if (!params.params().empty())
569 os << "[" << from_utf8(params.params()) << "]";
570 os << '{' << from_utf8(incfile) << '}';
572 runparams.exportdata->addExternalFile(tex_format, writefile,
575 // \include don't want extension and demands that the
576 // file really have .tex
577 incfile = changeExtension(incfile, string());
578 incfile = latex_path(incfile);
580 os << '\\' << from_ascii(params().getCmdName()) << '{'
581 << from_utf8(incfile) << '}';
588 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
590 if (isVerbatim(params()) || isListings(params())) {
591 os << '[' << screenLabel() << '\n';
592 // FIXME: We don't know the encoding of the file, default to UTF-8.
593 os << includedFilename(buffer(), params()).fileContents("UTF-8");
595 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
597 docstring const str = '[' + screenLabel() + ']';
604 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
606 string incfile = to_utf8(params()["filename"]);
608 // Do nothing if no file name has been specified
612 string const included_file = includedFilename(buffer(), params()).absFilename();
614 // Check we're not trying to include ourselves.
615 // FIXME RECURSIVE INCLUDE
616 // This isn't sufficient, as the inclusion could be downstream.
617 // But it'll have to do for now.
618 if (buffer().absFileName() == included_file) {
619 Alert::error(_("Recursive input"),
620 bformat(_("Attempted to include file %1$s in itself! "
621 "Ignoring inclusion."), from_utf8(incfile)));
625 // write it to a file (so far the complete file)
626 string const exportfile = changeExtension(incfile, ".sgml");
627 DocFileName writefile(changeExtension(included_file, ".sgml"));
629 if (loadIfNeeded(buffer(), params())) {
630 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
632 string const mangled = writefile.mangledFilename();
633 writefile = makeAbsPath(mangled,
634 buffer().masterBuffer()->temppath());
638 LYXERR(Debug::LATEX, "incfile:" << incfile);
639 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
640 LYXERR(Debug::LATEX, "writefile:" << writefile);
642 tmp->makeDocBookFile(writefile, runparams, true);
645 runparams.exportdata->addExternalFile("docbook", writefile,
647 runparams.exportdata->addExternalFile("docbook-xml", writefile,
650 if (isVerbatim(params()) || isListings(params())) {
651 os << "<inlinegraphic fileref=\""
652 << '&' << include_label << ';'
653 << "\" format=\"linespecific\">";
655 os << '&' << include_label << ';';
661 void InsetInclude::validate(LaTeXFeatures & features) const
663 string incfile = to_utf8(params()["filename"]);
666 LASSERT(&buffer() == &features.buffer(), /**/);
668 string const included_file =
669 includedFilename(buffer(), params()).absFilename();
671 if (isLyXFilename(included_file))
672 writefile = changeExtension(included_file, ".sgml");
674 writefile = included_file;
676 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
677 incfile = DocFileName(writefile).mangledFilename();
678 writefile = makeAbsPath(incfile,
679 buffer().masterBuffer()->temppath()).absFilename();
682 features.includeFile(include_label, writefile);
684 if (isVerbatim(params()))
685 features.require("verbatim");
686 else if (isListings(params()))
687 features.require("listings");
689 // Here we must do the fun stuff...
690 // Load the file in the include if it needs
692 if (loadIfNeeded(buffer(), params())) {
694 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
695 // make sure the buffer isn't us
696 // FIXME RECURSIVE INCLUDES
697 // This is not sufficient, as recursive includes could be
698 // more than a file away. But it will do for now.
699 if (tmp && tmp != &buffer()) {
700 // We must temporarily change features.buffer,
701 // otherwise it would always be the master buffer,
702 // and nested includes would not work.
703 features.setBuffer(*tmp);
704 tmp->validate(features);
705 features.setBuffer(buffer());
711 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
712 InsetIterator const & /*di*/) const
714 if (loadIfNeeded(buffer(), params())) {
715 string const included_file = includedFilename(buffer(), params()).absFilename();
716 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
717 BiblioInfo const & newkeys = tmp->localBibInfo();
718 keys.mergeBiblioInfo(newkeys);
723 void InsetInclude::updateBibfilesCache()
725 Buffer * const tmp = getChildBuffer(buffer(), params());
728 tmp->updateBibfilesCache();
729 tmp->setParent(&buffer());
734 support::FileNameList const &
735 InsetInclude::getBibfilesCache(Buffer const & buffer) const
737 Buffer * const tmp = getChildBuffer(buffer, params());
740 support::FileNameList const & cache = tmp->getBibfilesCache();
741 tmp->setParent(&buffer);
744 static support::FileNameList const empty;
749 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
751 LASSERT(mi.base.bv, /**/);
753 bool use_preview = false;
754 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
755 graphics::PreviewImage const * pimage =
756 preview_->getPreviewImage(mi.base.bv->buffer());
757 use_preview = pimage && pimage->image();
761 preview_->metrics(mi, dim);
765 button_.update(screenLabel(), true);
767 button_.metrics(mi, dim);
770 Box b(0, dim.wid, -dim.asc, dim.des);
775 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
777 LASSERT(pi.base.bv, /**/);
779 bool use_preview = false;
780 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
781 graphics::PreviewImage const * pimage =
782 preview_->getPreviewImage(pi.base.bv->buffer());
783 use_preview = pimage && pimage->image();
787 preview_->draw(pi, x, y);
789 button_.draw(pi, x, y);
793 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
795 return from_ascii("context-include");
799 Inset::DisplayType InsetInclude::display() const
801 return type(params()) == INPUT ? Inline : AlignCenter;
810 void InsetInclude::fileChanged() const
812 Buffer const * const buffer = updateFrontend();
816 preview_->removePreview(*buffer);
817 add_preview(*preview_.get(), *this, *buffer);
818 preview_->startLoading(*buffer);
824 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
826 FileName const included_file = includedFilename(buffer, params);
828 return type(params) == INPUT && params.preview() &&
829 included_file.isReadableFile();
833 docstring latexString(InsetInclude const & inset)
836 // We don't need to set runparams.encoding since this will be done
837 // by latex() anyway.
838 OutputParams runparams(0);
839 runparams.flavor = OutputParams::LATEX;
840 inset.latex(os, runparams);
846 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
847 Buffer const & buffer)
849 InsetCommandParams const & params = inset.params();
850 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
851 preview_wanted(params, buffer)) {
852 renderer.setAbsFile(includedFilename(buffer, params));
853 docstring const snippet = latexString(inset);
854 renderer.addPreview(snippet, buffer);
861 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
863 Buffer const & buffer = ploader.buffer();
864 if (!preview_wanted(params(), buffer))
866 preview_->setAbsFile(includedFilename(buffer, params()));
867 docstring const snippet = latexString(*this);
868 preview_->addPreview(snippet, ploader);
872 void InsetInclude::addToToc(DocIterator const & cpit)
874 TocBackend & backend = buffer().tocBackend();
876 if (isListings(params())) {
878 label_->addToToc(cpit);
880 InsetListingsParams p(to_utf8(params()["lstparams"]));
881 string caption = p.getParamValue("caption");
884 Toc & toc = backend.toc("listing");
885 docstring str = convert<docstring>(toc.size() + 1)
886 + ". " + from_utf8(caption);
887 DocIterator pit = cpit;
888 toc.push_back(TocItem(pit, 0, str));
891 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
895 Toc & toc = backend.toc("child");
896 docstring str = childbuffer->fileName().displayName();
897 toc.push_back(TocItem(cpit, 0, str));
899 TocList & toclist = backend.tocs();
900 childbuffer->tocBackend().update();
901 TocList const & childtoclist = childbuffer->tocBackend().tocs();
902 TocList::const_iterator it = childtoclist.begin();
903 TocList::const_iterator const end = childtoclist.end();
904 for(; it != end; ++it)
905 toclist[it->first].insert(toclist[it->first].end(),
906 it->second.begin(), it->second.end());
910 void InsetInclude::updateLabels(ParIterator const & it)
912 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
914 childbuffer->updateLabels(true);
917 if (!isListings(params()))
921 label_->updateLabels(it);
923 InsetListingsParams const par(to_utf8(params()["lstparams"]));
924 if (par.getParamValue("caption").empty()) {
925 listings_label_ = buffer().B_("Program Listing");
928 Buffer const & master = *buffer().masterBuffer();
929 Counters & counters = master.params().documentClass().counters();
930 docstring const cnt = from_ascii("listing");
931 listings_label_ = master.B_("Program Listing");
932 if (counters.hasCounter(cnt)) {
934 listings_label_ += " " + convert<docstring>(counters.value(cnt));