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)),
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)),
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 string const masterFilename(Buffer const & buffer)
235 return buffer.getMasterBuffer()->fileName();
239 string const parentFilename(Buffer const & buffer)
241 return buffer.fileName();
245 FileName const includedFilename(Buffer const & buffer,
246 InsetCommandParams const & params)
248 return makeAbsPath(to_utf8(params["filename"]),
249 onlyPath(parentFilename(buffer)));
253 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
258 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
263 if (preview_->monitoring())
264 preview_->stopMonitoring();
266 if (type(params_) == INPUT)
267 add_preview(*preview_, *this, buffer);
271 auto_ptr<Inset> InsetInclude::doClone() const
273 return auto_ptr<Inset>(new InsetInclude(*this));
277 void InsetInclude::write(Buffer const &, ostream & os) const
283 void InsetInclude::write(ostream & os) const
285 os << "Include " << to_utf8(params_.getCommand()) << '\n'
286 << "preview " << convert<string>(params_.preview()) << '\n';
290 void InsetInclude::read(Buffer const &, Lexer & lex)
296 void InsetInclude::read(Lexer & lex)
300 string const command = lex.getString();
301 params_.scanCommand(command);
306 token = lex.getString();
307 if (token == "\\end_inset")
309 if (token == "preview") {
311 params_.preview(lex.getBool());
313 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
315 if (token != "\\end_inset") {
316 lex.printError("Missing \\end_inset at this point. "
322 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
326 switch (type(params_)) {
328 temp += buf.B_("Input");
331 temp += buf.B_("Verbatim Input");
334 temp += buf.B_("Verbatim Input*");
337 temp += buf.B_("Include");
340 temp += buf.B_("Program Listing");
346 if (params_["filename"].empty())
349 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
357 /// return the child buffer if the file is a LyX doc and is loaded
358 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
360 if (isVerbatim(params) || isListings(params))
363 string const included_file = includedFilename(buffer, params).absFilename();
364 if (!isLyXFilename(included_file))
367 Buffer * childBuffer = theBufferList().getBuffer(included_file);
369 //FIXME RECURSIVE INCLUDES
370 if (childBuffer == & buffer)
372 else return childBuffer;
376 /// return true if the file is or got loaded.
377 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
379 if (isVerbatim(params) || isListings(params))
382 FileName const included_file = includedFilename(buffer, params);
383 if (!isLyXFilename(included_file.absFilename()))
386 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
388 // the readonly flag can/will be wrong, not anymore I think.
389 if (!fs::exists(included_file.toFilesystemEncoding()))
391 buf = theBufferList().newBuffer(included_file.absFilename());
392 if (!loadLyXFile(buf, included_file))
396 buf->setParentName(parentFilename(buffer));
404 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
405 OutputParams const & runparams) const
407 string incfile(to_utf8(params_["filename"]));
409 // Do nothing if no file name has been specified
413 FileName const included_file(includedFilename(buffer, params_));
415 //Check we're not trying to include ourselves.
416 //FIXME RECURSIVE INCLUDE
417 //This isn't sufficient, as the inclusion could be downstream.
418 //But it'll have to do for now.
419 if (buffer.fileName() == included_file.toFilesystemEncoding()) {
420 Alert::error(_("Recursive input"),
421 bformat(_("Attempted to include file %1$s in itself! "
422 "Ignoring inclusion."), from_utf8(incfile)));
426 Buffer const * const m_buffer = buffer.getMasterBuffer();
428 // if incfile is relative, make it relative to the master
430 if (!absolutePath(incfile)) {
432 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
433 from_utf8(m_buffer->filePath())));
436 // write it to a file (so far the complete file)
437 string const exportfile = changeExtension(incfile, ".tex");
438 string const mangled = DocFileName(changeExtension(included_file.absFilename(),
439 ".tex")).mangledFilename();
440 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
444 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
445 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
446 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
448 if (runparams.inComment || runparams.dryrun)
449 // Don't try to load or copy the file
451 else if (loadIfNeeded(buffer, params_)) {
452 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
454 if (tmp->params().textclass != m_buffer->params().textclass) {
456 docstring text = bformat(_("Included file `%1$s'\n"
457 "has textclass `%2$s'\n"
458 "while parent file has textclass `%3$s'."),
459 makeDisplayPath(included_file.absFilename()),
460 from_utf8(tmp->params().getTextClass().name()),
461 from_utf8(m_buffer->params().getTextClass().name()));
462 Alert::warning(_("Different textclasses"), text);
466 tmp->markDepClean(m_buffer->temppath());
469 #warning handle non existing files
470 #warning Second argument is irrelevant!
471 // since only_body is true, makeLaTeXFile will not look at second
472 // argument. Should we set it to string(), or should makeLaTeXFile
473 // make use of it somehow? (JMarc 20031002)
475 // The included file might be written in a different encoding
476 Encoding const * const oldEnc = runparams.encoding;
477 runparams.encoding = &tmp->params().encoding();
478 tmp->makeLaTeXFile(writefile,
479 onlyPath(masterFilename(buffer)),
481 runparams.encoding = oldEnc;
483 // Copy the file to the temp dir, so that .aux files etc.
484 // are not created in the original dir. Files included by
485 // this file will be found via input@path, see ../Buffer.cpp.
486 unsigned long const checksum_in = sum(included_file);
487 unsigned long const checksum_out = sum(writefile);
489 if (checksum_in != checksum_out) {
490 if (!copy(included_file, writefile)) {
493 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
494 "into the temporary directory."),
495 from_utf8(included_file.absFilename())))
502 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
503 "latex" : "pdflatex";
504 if (isVerbatim(params_)) {
505 incfile = latex_path(incfile);
507 os << '\\' << from_ascii(params_.getCmdName()) << '{'
508 << from_utf8(incfile) << '}';
509 } else if (type(params_) == INPUT) {
510 runparams.exportdata->addExternalFile(tex_format, writefile,
513 // \input wants file with extension (default is .tex)
514 if (!isLyXFilename(included_file.absFilename())) {
515 incfile = latex_path(incfile);
517 os << '\\' << from_ascii(params_.getCmdName())
518 << '{' << from_utf8(incfile) << '}';
520 incfile = changeExtension(incfile, ".tex");
521 incfile = latex_path(incfile);
523 os << '\\' << from_ascii(params_.getCmdName())
524 << '{' << from_utf8(incfile) << '}';
526 } else if (type(params_) == LISTINGS) {
527 os << '\\' << from_ascii(params_.getCmdName());
528 string opt = params_.getOptions();
529 // opt is set in QInclude dialog and should have passed validation.
530 InsetListingsParams params(opt);
531 if (!params.params().empty())
532 os << "[" << from_utf8(params.encodedString()) << "]";
533 os << '{' << from_utf8(incfile) << '}';
535 runparams.exportdata->addExternalFile(tex_format, writefile,
538 // \include don't want extension and demands that the
539 // file really have .tex
540 incfile = changeExtension(incfile, string());
541 incfile = latex_path(incfile);
543 os << '\\' << from_ascii(params_.getCmdName()) << '{'
544 << from_utf8(incfile) << '}';
551 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
552 OutputParams const &) const
554 if (isVerbatim(params_) || isListings(params_)) {
555 os << '[' << getScreenLabel(buffer) << '\n';
556 // FIXME: We don't know the encoding of the file
557 docstring const str =
558 from_utf8(getFileContents(includedFilename(buffer, params_)));
561 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
563 docstring const str = '[' + getScreenLabel(buffer) + ']';
570 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
571 OutputParams const & runparams) const
573 string incfile = to_utf8(params_["filename"]);
575 // Do nothing if no file name has been specified
579 string const included_file = includedFilename(buffer, params_).absFilename();
581 //Check we're not trying to include ourselves.
582 //FIXME RECURSIVE INCLUDE
583 //This isn't sufficient, as the inclusion could be downstream.
584 //But it'll have to do for now.
585 if (buffer.fileName() == included_file) {
586 Alert::error(_("Recursive input"),
587 bformat(_("Attempted to include file %1$s in itself! "
588 "Ignoring inclusion."), from_utf8(incfile)));
592 // write it to a file (so far the complete file)
593 string const exportfile = changeExtension(incfile, ".sgml");
594 DocFileName writefile(changeExtension(included_file, ".sgml"));
596 if (loadIfNeeded(buffer, params_)) {
597 Buffer * tmp = theBufferList().getBuffer(included_file);
599 string const mangled = writefile.mangledFilename();
600 writefile = makeAbsPath(mangled,
601 buffer.getMasterBuffer()->temppath());
605 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
606 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
607 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
609 tmp->makeDocBookFile(writefile, runparams, true);
612 runparams.exportdata->addExternalFile("docbook", writefile,
614 runparams.exportdata->addExternalFile("docbook-xml", writefile,
617 if (isVerbatim(params_) || isListings(params_)) {
618 os << "<inlinegraphic fileref=\""
619 << '&' << include_label << ';'
620 << "\" format=\"linespecific\">";
622 os << '&' << include_label << ';';
628 void InsetInclude::validate(LaTeXFeatures & features) const
630 string incfile(to_utf8(params_["filename"]));
633 Buffer const & buffer = features.buffer();
635 string const included_file = includedFilename(buffer, params_).absFilename();
637 if (isLyXFilename(included_file))
638 writefile = changeExtension(included_file, ".sgml");
640 writefile = included_file;
642 if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
643 incfile = DocFileName(writefile).mangledFilename();
644 writefile = makeAbsPath(incfile,
645 buffer.getMasterBuffer()->temppath()).absFilename();
648 features.includeFile(include_label, writefile);
650 if (isVerbatim(params_))
651 features.require("verbatim");
652 else if (isListings(params_))
653 features.require("listings");
655 // Here we must do the fun stuff...
656 // Load the file in the include if it needs
658 if (loadIfNeeded(buffer, params_)) {
660 Buffer * const tmp = theBufferList().getBuffer(included_file);
661 // make sure the buffer isn't us
662 // FIXME RECURSIVE INCLUDES
663 // This is not sufficient, as recursive includes could be
664 // more than a file away. But it will do for now.
665 if (tmp && tmp != & buffer) {
666 // We must temporarily change features.buffer,
667 // otherwise it would always be the master buffer,
668 // and nested includes would not work.
669 features.setBuffer(*tmp);
670 tmp->validate(features);
671 features.setBuffer(buffer);
677 void InsetInclude::getLabelList(Buffer const & buffer,
678 std::vector<docstring> & list) const
680 if (isListings(params_)) {
681 InsetListingsParams params(params_.getOptions());
682 string label = params.getParamValue("label");
684 list.push_back(from_utf8(label));
686 else if (loadIfNeeded(buffer, params_)) {
687 string const included_file = includedFilename(buffer, params_).absFilename();
688 Buffer * tmp = theBufferList().getBuffer(included_file);
689 tmp->setParentName("");
690 tmp->getLabelList(list);
691 tmp->setParentName(parentFilename(buffer));
696 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
697 std::vector<std::pair<string, docstring> > & keys) const
699 if (loadIfNeeded(buffer, params_)) {
700 string const included_file = includedFilename(buffer, params_).absFilename();
701 Buffer * tmp = theBufferList().getBuffer(included_file);
702 tmp->setParentName("");
703 tmp->fillWithBibKeys(keys);
704 tmp->setParentName(parentFilename(buffer));
709 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
711 Buffer * const tmp = getChildBuffer(buffer, params_);
713 tmp->setParentName("");
714 tmp->updateBibfilesCache();
715 tmp->setParentName(parentFilename(buffer));
720 std::vector<FileName> const &
721 InsetInclude::getBibfilesCache(Buffer const & buffer) const
723 Buffer * const tmp = getChildBuffer(buffer, params_);
725 tmp->setParentName("");
726 std::vector<FileName> const & cache = tmp->getBibfilesCache();
727 tmp->setParentName(parentFilename(buffer));
730 static std::vector<FileName> const empty;
735 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
737 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
739 bool use_preview = false;
740 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
741 graphics::PreviewImage const * pimage =
742 preview_->getPreviewImage(*mi.base.bv->buffer());
743 use_preview = pimage && pimage->image();
747 preview_->metrics(mi, dim);
751 button_.update(getScreenLabel(*mi.base.bv->buffer()),
754 button_.metrics(mi, dim);
757 Box b(0, dim.wid, -dim.asc, dim.des);
760 bool const changed = dim_ != dim;
766 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
768 setPosCache(pi, x, y);
770 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
772 bool use_preview = false;
773 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
774 graphics::PreviewImage const * pimage =
775 preview_->getPreviewImage(*pi.base.bv->buffer());
776 use_preview = pimage && pimage->image();
780 preview_->draw(pi, x, y);
782 button_.draw(pi, x, y);
786 Inset::DisplayType InsetInclude::display() const
788 return type(params_) == INPUT ? Inline : AlignCenter;
797 void InsetInclude::fileChanged() const
799 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
803 Buffer const & buffer = *buffer_ptr;
804 preview_->removePreview(buffer);
805 add_preview(*preview_.get(), *this, buffer);
806 preview_->startLoading(buffer);
812 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
814 FileName const included_file = includedFilename(buffer, params);
816 return type(params) == INPUT && params.preview() &&
817 isFileReadable(included_file);
821 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
824 // We don't need to set runparams.encoding since this will be done
825 // by latex() anyway.
826 OutputParams runparams(0);
827 runparams.flavor = OutputParams::LATEX;
828 inset.latex(buffer, os, runparams);
834 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
835 Buffer const & buffer)
837 InsetCommandParams const & params = inset.params();
838 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
839 preview_wanted(params, buffer)) {
840 renderer.setAbsFile(includedFilename(buffer, params));
841 docstring const snippet = latex_string(inset, buffer);
842 renderer.addPreview(snippet, buffer);
849 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
851 Buffer const & buffer = ploader.buffer();
852 if (preview_wanted(params(), buffer)) {
853 preview_->setAbsFile(includedFilename(buffer, params()));
854 docstring const snippet = latex_string(*this, buffer);
855 preview_->addPreview(snippet, ploader);
860 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
862 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
866 TocList const & childtoclist = childbuffer->tocBackend().tocs();
867 TocList::const_iterator it = childtoclist.begin();
868 TocList::const_iterator const end = childtoclist.end();
869 for(; it != end; ++it)
870 toclist[it->first].insert(toclist[it->first].end(),
871 it->second.begin(), it->second.end());
875 void InsetInclude::updateLabels(Buffer const & buffer) const
877 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
881 lyx::updateLabels(*childbuffer, true);
885 string const InsetIncludeMailer::name_("include");
887 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
892 string const InsetIncludeMailer::inset2string(Buffer const &) const
894 return params2string(inset_.params());
898 void InsetIncludeMailer::string2params(string const & in,
899 InsetCommandParams & params)
905 istringstream data(in);
911 if (!lex || name != name_)
912 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
914 // This is part of the inset proper that is usually swallowed
915 // by Text::readInset
918 if (!lex || id != "Include")
919 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
921 InsetInclude inset(params);
923 params = inset.params();
928 InsetIncludeMailer::params2string(InsetCommandParams const & params)
930 InsetInclude inset(params);
932 data << name_ << ' ';
934 data << "\\end_inset\n";