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"
23 #include "DispatchResult.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TocBackend.h"
36 #include "frontends/alert.h"
37 #include "frontends/Painter.h"
39 #include "graphics/PreviewImage.h"
40 #include "graphics/PreviewLoader.h"
42 #include "insets/RenderPreview.h"
43 #include "insets/InsetListingsParams.h"
45 #include "support/docstream.h"
46 #include "support/filetools.h"
47 #include "support/lstrings.h" // contains
48 #include "support/lyxalgo.h"
49 #include "support/lyxlib.h"
50 #include "support/convert.h"
52 #include <boost/bind.hpp>
57 using support::addName;
58 using support::absolutePath;
59 using support::bformat;
60 using support::changeExtension;
61 using support::contains;
63 using support::DocFileName;
64 using support::FileName;
65 using support::getVectorFromString;
66 using support::isLyXFilename;
67 using support::isValidLaTeXFilename;
68 using support::latex_path;
69 using support::makeAbsPath;
70 using support::makeRelPath;
71 using support::onlyFilename;
72 using support::onlyPath;
73 using support::prefixIs;
80 using std::istringstream;
82 using std::ostringstream;
85 namespace Alert = frontend::Alert;
90 docstring const uniqueID()
92 static unsigned int seed = 1000;
93 return "file" + convert<docstring>(++seed);
97 /// the type of inclusion
99 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
103 Types type(std::string const & s)
107 if (s == "verbatiminput")
109 if (s == "verbatiminput*")
111 if (s == "lstinputlisting")
119 Types type(InsetCommandParams const & params)
121 return type(params.getCmdName());
125 bool isListings(InsetCommandParams const & params)
127 return type(params) == LISTINGS;
131 bool isVerbatim(InsetCommandParams const & params)
133 Types const t = type(params);
134 return t == VERB || t == VERBAST;
138 bool isInputOrInclude(InsetCommandParams const & params)
140 Types const t = type(params);
141 return t == INPUT || t == INCLUDE;
147 InsetInclude::InsetInclude(InsetCommandParams const & p)
148 : InsetCommand(p, "include"), include_label(uniqueID()),
149 preview_(new RenderMonitoredPreview(this)), set_label_(false)
151 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
155 InsetInclude::InsetInclude(InsetInclude const & other)
156 : InsetCommand(other), include_label(other.include_label),
157 preview_(new RenderMonitoredPreview(this)), set_label_(false)
159 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
163 CommandInfo const * InsetInclude::findInfo(std::string const & /* cmdName */)
165 // This is only correct for the case of listings, but it'll do for now.
166 // In the other cases, this second parameter should just be empty.
167 static const char * const paramnames[] = {"filename", "lstparams", ""};
168 static const bool isoptional[] = {false, true};
169 static const CommandInfo info = {2, paramnames, isoptional};
174 bool InsetInclude::isCompatibleCommand(std::string const & s)
176 return type(s) != NONE;
180 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
182 switch (cmd.action) {
184 case LFUN_INSET_MODIFY: {
185 InsetCommandParams p(INCLUDE_CODE);
186 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
187 if (!p.getCmdName().empty()) {
189 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
190 InsetListingsParams par_new(to_utf8(p["lstparams"]));
191 if (par_old.getParamValue("label") !=
192 par_new.getParamValue("label")
193 && !par_new.getParamValue("label").empty())
194 cur.bv().buffer().changeRefsIfUnique(
195 from_utf8(par_old.getParamValue("label")),
196 from_utf8(par_new.getParamValue("label")),
199 set(p, cur.buffer());
200 cur.buffer().updateBibfilesCache();
206 //pass everything else up the chain
208 InsetCommand::doDispatch(cur, cmd);
216 FileName const masterFileName(Buffer const & buffer)
218 return buffer.masterBuffer()->fileName();
222 string const parentFilename(Buffer const & buffer)
224 return buffer.absFileName();
228 FileName const includedFilename(Buffer const & buffer,
229 InsetCommandParams const & params)
231 return makeAbsPath(to_utf8(params["filename"]),
232 onlyPath(parentFilename(buffer)));
236 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
241 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
246 if (preview_->monitoring())
247 preview_->stopMonitoring();
249 if (type(params()) == INPUT)
250 add_preview(*preview_, *this, buffer);
254 Inset * InsetInclude::clone() const
256 return new InsetInclude(*this);
260 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
264 switch (type(params())) {
266 temp = buf.B_("Input");
269 temp = buf.B_("Verbatim Input");
272 temp = buf.B_("Verbatim Input*");
275 temp = buf.B_("Include");
278 temp = listings_label_;
285 if (params()["filename"].empty())
288 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
296 /// return the child buffer if the file is a LyX doc and is loaded
297 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
299 if (isVerbatim(params) || isListings(params))
302 string const included_file = includedFilename(buffer, params).absFilename();
303 if (!isLyXFilename(included_file))
306 Buffer * childBuffer = theBufferList().getBuffer(included_file);
308 //FIXME RECURSIVE INCLUDES
309 if (childBuffer == & buffer)
318 /// return true if the file is or got loaded.
319 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
321 if (isVerbatim(params) || isListings(params))
324 string const parent_filename = parent.absFileName();
325 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
326 onlyPath(parent_filename));
328 if (!isLyXFilename(included_file.absFilename()))
331 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
333 // the readonly flag can/will be wrong, not anymore I think.
334 if (!included_file.exists())
337 child = theBufferList().newBuffer(included_file.absFilename());
338 if (!child->loadLyXFile(included_file)) {
339 //close the buffer we just opened
340 theBufferList().close(child, false);
344 child->setParentName(parent_filename);
349 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
350 OutputParams const & runparams) const
352 string incfile(to_utf8(params()["filename"]));
354 // Do nothing if no file name has been specified
358 FileName const included_file = includedFilename(buffer, params());
360 //Check we're not trying to include ourselves.
361 //FIXME RECURSIVE INCLUDE
362 //This isn't sufficient, as the inclusion could be downstream.
363 //But it'll have to do for now.
364 if (isInputOrInclude(params()) &&
365 buffer.absFileName() == included_file.absFilename())
367 Alert::error(_("Recursive input"),
368 bformat(_("Attempted to include file %1$s in itself! "
369 "Ignoring inclusion."), from_utf8(incfile)));
373 Buffer const * const masterBuffer = buffer.masterBuffer();
375 // if incfile is relative, make it relative to the master
377 if (!absolutePath(incfile)) {
379 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
380 from_utf8(masterBuffer->filePath())));
383 // write it to a file (so far the complete file)
384 string const exportfile = changeExtension(incfile, ".tex");
385 string const mangled =
386 DocFileName(changeExtension(included_file.absFilename(),".tex")).
388 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
392 else if (!isValidLaTeXFilename(incfile)) {
393 frontend::Alert::warning(_("Invalid filename"),
394 _("The following filename is likely to cause trouble "
395 "when running the exported file through LaTeX: ") +
398 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
399 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
400 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
402 if (runparams.inComment || runparams.dryrun) {
403 //Don't try to load or copy the file if we're
404 //in a comment or doing a dryrun
405 } else if (isInputOrInclude(params()) &&
406 isLyXFilename(included_file.absFilename())) {
407 //if it's a LyX file and we're inputting or including,
408 //try to load it so we can write the associated latex
409 if (!loadIfNeeded(buffer, params()))
412 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
414 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
416 docstring text = bformat(_("Included file `%1$s'\n"
417 "has textclass `%2$s'\n"
418 "while parent file has textclass `%3$s'."),
419 included_file.displayName(),
420 from_utf8(tmp->params().getTextClass().name()),
421 from_utf8(masterBuffer->params().getTextClass().name()));
422 Alert::warning(_("Different textclasses"), text);
426 // Make sure modules used in child are all included in master
427 //FIXME It might be worth loading the children's modules into the master
428 //over in BufferParams rather than doing this check.
429 vector<string> const masterModules = masterBuffer->params().getModules();
430 vector<string> const childModules = tmp->params().getModules();
431 vector<string>::const_iterator it = childModules.begin();
432 vector<string>::const_iterator end = childModules.end();
433 for (; it != end; ++it) {
434 string const module = *it;
435 vector<string>::const_iterator found =
436 find(masterModules.begin(), masterModules.end(), module);
437 if (found != masterModules.end()) {
438 docstring text = bformat(_("Included file `%1$s'\n"
439 "uses module `%2$s'\n"
440 "which is not used in parent file."),
441 included_file.displayName(), from_utf8(module));
442 Alert::warning(_("Module not found"), text);
446 tmp->markDepClean(masterBuffer->temppath());
448 // FIXME: handle non existing files
449 // FIXME: Second argument is irrelevant!
450 // since only_body is true, makeLaTeXFile will not look at second
451 // argument. Should we set it to string(), or should makeLaTeXFile
452 // make use of it somehow? (JMarc 20031002)
453 // The included file might be written in a different encoding
454 Encoding const * const oldEnc = runparams.encoding;
455 runparams.encoding = &tmp->params().encoding();
456 tmp->makeLaTeXFile(writefile,
457 masterFileName(buffer).onlyPath(),
459 runparams.encoding = oldEnc;
461 // In this case, it's not a LyX file, so we copy the file
462 // to the temp dir, so that .aux files etc. are not created
463 // in the original dir. Files included by this file will be
464 // found via input@path, see ../Buffer.cpp.
465 unsigned long const checksum_in = sum(included_file);
466 unsigned long const checksum_out = sum(writefile);
468 if (checksum_in != checksum_out) {
469 if (!copy(included_file, writefile)) {
472 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
473 "into the temporary directory."),
474 from_utf8(included_file.absFilename())))
481 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
482 "latex" : "pdflatex";
483 if (isVerbatim(params())) {
484 incfile = latex_path(incfile);
486 os << '\\' << from_ascii(params().getCmdName()) << '{'
487 << from_utf8(incfile) << '}';
488 } else if (type(params()) == INPUT) {
489 runparams.exportdata->addExternalFile(tex_format, writefile,
492 // \input wants file with extension (default is .tex)
493 if (!isLyXFilename(included_file.absFilename())) {
494 incfile = latex_path(incfile);
496 os << '\\' << from_ascii(params().getCmdName())
497 << '{' << from_utf8(incfile) << '}';
499 incfile = changeExtension(incfile, ".tex");
500 incfile = latex_path(incfile);
502 os << '\\' << from_ascii(params().getCmdName())
503 << '{' << from_utf8(incfile) << '}';
505 } else if (type(params()) == LISTINGS) {
506 os << '\\' << from_ascii(params().getCmdName());
507 string const opt = to_utf8(params()["lstparams"]);
508 // opt is set in QInclude dialog and should have passed validation.
509 InsetListingsParams params(opt);
510 if (!params.params().empty())
511 os << "[" << from_utf8(params.params()) << "]";
512 os << '{' << from_utf8(incfile) << '}';
514 runparams.exportdata->addExternalFile(tex_format, writefile,
517 // \include don't want extension and demands that the
518 // file really have .tex
519 incfile = changeExtension(incfile, string());
520 incfile = latex_path(incfile);
522 os << '\\' << from_ascii(params().getCmdName()) << '{'
523 << from_utf8(incfile) << '}';
530 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
531 OutputParams const &) const
533 if (isVerbatim(params()) || isListings(params())) {
534 os << '[' << getScreenLabel(buffer) << '\n';
535 // FIXME: We don't know the encoding of the file
536 docstring const str =
537 from_utf8(includedFilename(buffer, params()).fileContents());
540 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
542 docstring const str = '[' + getScreenLabel(buffer) + ']';
549 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
550 OutputParams const & runparams) const
552 string incfile = to_utf8(params()["filename"]);
554 // Do nothing if no file name has been specified
558 string const included_file = includedFilename(buffer, params()).absFilename();
560 //Check we're not trying to include ourselves.
561 //FIXME RECURSIVE INCLUDE
562 //This isn't sufficient, as the inclusion could be downstream.
563 //But it'll have to do for now.
564 if (buffer.absFileName() == included_file) {
565 Alert::error(_("Recursive input"),
566 bformat(_("Attempted to include file %1$s in itself! "
567 "Ignoring inclusion."), from_utf8(incfile)));
571 // write it to a file (so far the complete file)
572 string const exportfile = changeExtension(incfile, ".sgml");
573 DocFileName writefile(changeExtension(included_file, ".sgml"));
575 if (loadIfNeeded(buffer, params())) {
576 Buffer * tmp = theBufferList().getBuffer(included_file);
578 string const mangled = writefile.mangledFilename();
579 writefile = makeAbsPath(mangled,
580 buffer.masterBuffer()->temppath());
584 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
585 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
586 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
588 tmp->makeDocBookFile(writefile, runparams, true);
591 runparams.exportdata->addExternalFile("docbook", writefile,
593 runparams.exportdata->addExternalFile("docbook-xml", writefile,
596 if (isVerbatim(params()) || isListings(params())) {
597 os << "<inlinegraphic fileref=\""
598 << '&' << include_label << ';'
599 << "\" format=\"linespecific\">";
601 os << '&' << include_label << ';';
607 void InsetInclude::validate(LaTeXFeatures & features) const
609 string incfile = to_utf8(params()["filename"]);
612 Buffer const & buffer = features.buffer();
614 string const included_file = includedFilename(buffer, params()).absFilename();
616 if (isLyXFilename(included_file))
617 writefile = changeExtension(included_file, ".sgml");
619 writefile = included_file;
621 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
622 incfile = DocFileName(writefile).mangledFilename();
623 writefile = makeAbsPath(incfile,
624 buffer.masterBuffer()->temppath()).absFilename();
627 features.includeFile(include_label, writefile);
629 if (isVerbatim(params()))
630 features.require("verbatim");
631 else if (isListings(params()))
632 features.require("listings");
634 // Here we must do the fun stuff...
635 // Load the file in the include if it needs
637 if (loadIfNeeded(buffer, params())) {
639 Buffer * const tmp = theBufferList().getBuffer(included_file);
640 // make sure the buffer isn't us
641 // FIXME RECURSIVE INCLUDES
642 // This is not sufficient, as recursive includes could be
643 // more than a file away. But it will do for now.
644 if (tmp && tmp != & buffer) {
645 // We must temporarily change features.buffer,
646 // otherwise it would always be the master buffer,
647 // and nested includes would not work.
648 features.setBuffer(*tmp);
649 tmp->validate(features);
650 features.setBuffer(buffer);
656 void InsetInclude::getLabelList(Buffer const & buffer,
657 std::vector<docstring> & list) const
659 if (isListings(params())) {
660 InsetListingsParams p(to_utf8(params()["lstparams"]));
661 string label = p.getParamValue("label");
663 list.push_back(from_utf8(label));
665 else if (loadIfNeeded(buffer, params())) {
666 string const included_file = includedFilename(buffer, params()).absFilename();
667 Buffer * tmp = theBufferList().getBuffer(included_file);
668 tmp->setParentName("");
669 tmp->getLabelList(list);
670 tmp->setParentName(parentFilename(buffer));
675 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
676 BiblioInfo & keys, InsetIterator const & /*di*/) const
678 if (loadIfNeeded(buffer, params())) {
679 string const included_file = includedFilename(buffer, params()).absFilename();
680 Buffer * tmp = theBufferList().getBuffer(included_file);
681 //FIXME This is kind of a dirty hack and should be made reasonable.
682 tmp->setParentName("");
683 keys.fillWithBibKeys(tmp);
684 tmp->setParentName(parentFilename(buffer));
689 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
691 Buffer * const tmp = getChildBuffer(buffer, params());
693 tmp->setParentName("");
694 tmp->updateBibfilesCache();
695 tmp->setParentName(parentFilename(buffer));
700 std::vector<FileName> const &
701 InsetInclude::getBibfilesCache(Buffer const & buffer) const
703 Buffer * const tmp = getChildBuffer(buffer, params());
705 tmp->setParentName("");
706 std::vector<FileName> const & cache = tmp->getBibfilesCache();
707 tmp->setParentName(parentFilename(buffer));
710 static std::vector<FileName> const empty;
715 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
717 BOOST_ASSERT(mi.base.bv);
719 bool use_preview = false;
720 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
721 graphics::PreviewImage const * pimage =
722 preview_->getPreviewImage(mi.base.bv->buffer());
723 use_preview = pimage && pimage->image();
727 preview_->metrics(mi, dim);
731 button_.update(getScreenLabel(mi.base.bv->buffer()),
734 button_.metrics(mi, dim);
737 Box b(0, dim.wid, -dim.asc, dim.des);
742 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
744 BOOST_ASSERT(pi.base.bv);
746 bool use_preview = false;
747 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
748 graphics::PreviewImage const * pimage =
749 preview_->getPreviewImage(pi.base.bv->buffer());
750 use_preview = pimage && pimage->image();
754 preview_->draw(pi, x, y);
756 button_.draw(pi, x, y);
760 Inset::DisplayType InsetInclude::display() const
762 return type(params()) == INPUT ? Inline : AlignCenter;
771 void InsetInclude::fileChanged() const
773 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
777 Buffer const & buffer = *buffer_ptr;
778 preview_->removePreview(buffer);
779 add_preview(*preview_.get(), *this, buffer);
780 preview_->startLoading(buffer);
786 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
788 FileName const included_file = includedFilename(buffer, params);
790 return type(params) == INPUT && params.preview() &&
791 included_file.isFileReadable();
795 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
798 // We don't need to set runparams.encoding since this will be done
799 // by latex() anyway.
800 OutputParams runparams(0);
801 runparams.flavor = OutputParams::LATEX;
802 inset.latex(buffer, os, runparams);
808 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
809 Buffer const & buffer)
811 InsetCommandParams const & params = inset.params();
812 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
813 preview_wanted(params, buffer)) {
814 renderer.setAbsFile(includedFilename(buffer, params));
815 docstring const snippet = latex_string(inset, buffer);
816 renderer.addPreview(snippet, buffer);
823 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
825 Buffer const & buffer = ploader.buffer();
826 if (preview_wanted(params(), buffer)) {
827 preview_->setAbsFile(includedFilename(buffer, params()));
828 docstring const snippet = latex_string(*this, buffer);
829 preview_->addPreview(snippet, ploader);
834 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
835 ParConstIterator const & pit) const
837 if (isListings(params())) {
838 InsetListingsParams p(to_utf8(params()["lstparams"]));
839 string caption = p.getParamValue("caption");
842 Toc & toc = toclist["listing"];
843 docstring const str = convert<docstring>(toc.size() + 1)
844 + ". " + from_utf8(caption);
845 // This inset does not have a valid ParConstIterator
846 // so it has to use the iterator of its parent paragraph
847 toc.push_back(TocItem(pit, 0, str));
850 Buffer const * const childbuffer = getChildBuffer(buffer, params());
854 TocList const & childtoclist = childbuffer->tocBackend().tocs();
855 TocList::const_iterator it = childtoclist.begin();
856 TocList::const_iterator const end = childtoclist.end();
857 for(; it != end; ++it)
858 toclist[it->first].insert(toclist[it->first].end(),
859 it->second.begin(), it->second.end());
863 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
865 Buffer const * const childbuffer = getChildBuffer(buffer, params());
867 lyx::updateLabels(*childbuffer, true);
868 else if (isListings(params())) {
869 InsetListingsParams const par(to_utf8(params()["lstparams"]));
870 if (par.getParamValue("caption").empty())
871 listings_label_.clear();
873 Counters & counters = buffer.params().getTextClass().counters();
874 docstring const cnt = from_ascii("listing");
875 if (counters.hasCounter(cnt)) {
877 listings_label_ = buffer.B_("Program Listing ")
878 + convert<docstring>(counters.value(cnt));
880 listings_label_ = buffer.B_("Program Listing");
886 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
887 EmbeddedFiles & files) const
889 // include and input are temprarily not considered.
890 if (isVerbatim(params()) || isListings(params()))
891 files.registerFile(includedFilename(buffer, params()).absFilename(),