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 InsetIncludeMailer(*this).showDialog(&cur.bv());
168 Inset::doDispatch(cur, cmd);
174 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
175 FuncStatus & flag) const
177 switch (cmd.action) {
179 case LFUN_INSET_MODIFY:
180 case LFUN_INSET_DIALOG_UPDATE:
185 return Inset::getStatus(cur, cmd, flag);
190 InsetCommandParams const & InsetInclude::params() const
198 /// the type of inclusion
208 Types type(InsetCommandParams const & params)
210 string const command_name = params.getCmdName();
212 if (command_name == "input")
214 if (command_name == "verbatiminput")
216 if (command_name == "verbatiminput*")
218 if (command_name == "lstinputlisting")
224 bool isVerbatim(InsetCommandParams const & params)
226 string const command_name = params.getCmdName();
227 return command_name == "verbatiminput" ||
228 command_name == "verbatiminput*";
232 string const masterFilename(Buffer const & buffer)
234 return buffer.getMasterBuffer()->fileName();
238 string const parentFilename(Buffer const & buffer)
240 return buffer.fileName();
244 FileName const includedFilename(Buffer const & buffer,
245 InsetCommandParams const & params)
247 return makeAbsPath(to_utf8(params["filename"]),
248 onlyPath(parentFilename(buffer)));
252 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
257 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
262 if (preview_->monitoring())
263 preview_->stopMonitoring();
265 if (type(params_) == INPUT)
266 add_preview(*preview_, *this, buffer);
270 auto_ptr<Inset> InsetInclude::doClone() const
272 return auto_ptr<Inset>(new InsetInclude(*this));
276 void InsetInclude::write(Buffer const &, ostream & os) const
282 void InsetInclude::write(ostream & os) const
284 os << "Include " << to_utf8(params_.getCommand()) << '\n'
285 << "preview " << convert<string>(params_.preview()) << '\n';
289 void InsetInclude::read(Buffer const &, Lexer & lex)
295 void InsetInclude::read(Lexer & lex)
299 string const command = lex.getString();
300 params_.scanCommand(command);
305 token = lex.getString();
306 if (token == "\\end_inset")
308 if (token == "preview") {
310 params_.preview(lex.getBool());
312 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
314 if (token != "\\end_inset") {
315 lex.printError("Missing \\end_inset at this point. "
321 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
325 switch (type(params_)) {
327 temp += buf.B_("Input");
330 temp += buf.B_("Verbatim Input");
333 temp += buf.B_("Verbatim Input*");
336 temp += buf.B_("Include");
339 temp += buf.B_("Program Listing");
345 if (params_["filename"].empty())
348 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
356 /// return the child buffer if the file is a LyX doc and is loaded
357 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
359 if (isVerbatim(params) || isListings(params))
362 string const included_file = includedFilename(buffer, params).absFilename();
363 if (!isLyXFilename(included_file))
366 Buffer * childBuffer = theBufferList().getBuffer(included_file);
368 //FIXME RECURSIVE INCLUDES
369 if (childBuffer == & buffer)
371 else return childBuffer;
375 /// return true if the file is or got loaded.
376 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
378 if (isVerbatim(params) || isListings(params))
381 FileName const included_file = includedFilename(buffer, params);
382 if (!isLyXFilename(included_file.absFilename()))
385 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
387 // the readonly flag can/will be wrong, not anymore I think.
388 if (!fs::exists(included_file.toFilesystemEncoding()))
390 buf = theBufferList().newBuffer(included_file.absFilename());
391 if (!loadLyXFile(buf, included_file))
395 buf->setParentName(parentFilename(buffer));
403 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
404 OutputParams const & runparams) const
406 string incfile(to_utf8(params_["filename"]));
408 // Do nothing if no file name has been specified
412 FileName const included_file(includedFilename(buffer, params_));
414 //Check we're not trying to include ourselves.
415 //FIXME RECURSIVE INCLUDE
416 //This isn't sufficient, as the inclusion could be downstream.
417 //But it'll have to do for now.
418 if (buffer.fileName() == included_file.toFilesystemEncoding()) {
419 Alert::error(_("Recursive input"),
420 bformat(_("Attempted to include file %1$s in itself! "
421 "Ignoring inclusion."), from_utf8(incfile)));
425 Buffer const * const m_buffer = buffer.getMasterBuffer();
427 // if incfile is relative, make it relative to the master
429 if (!absolutePath(incfile)) {
431 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
432 from_utf8(m_buffer->filePath())));
435 // write it to a file (so far the complete file)
436 string const exportfile = changeExtension(incfile, ".tex");
437 string const mangled = DocFileName(changeExtension(included_file.absFilename(),
438 ".tex")).mangledFilename();
439 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
443 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
444 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
445 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
447 if (runparams.inComment || runparams.dryrun)
448 // Don't try to load or copy the file
450 else if (loadIfNeeded(buffer, params_)) {
451 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
453 if (tmp->params().textclass != m_buffer->params().textclass) {
455 docstring text = bformat(_("Included file `%1$s'\n"
456 "has textclass `%2$s'\n"
457 "while parent file has textclass `%3$s'."),
458 makeDisplayPath(included_file.absFilename()),
459 from_utf8(tmp->params().getTextClass().name()),
460 from_utf8(m_buffer->params().getTextClass().name()));
461 Alert::warning(_("Different textclasses"), text);
465 tmp->markDepClean(m_buffer->temppath());
468 #warning handle non existing files
469 #warning Second argument is irrelevant!
470 // since only_body is true, makeLaTeXFile will not look at second
471 // argument. Should we set it to string(), or should makeLaTeXFile
472 // make use of it somehow? (JMarc 20031002)
474 // The included file might be written in a different encoding
475 Encoding const * const oldEnc = runparams.encoding;
476 runparams.encoding = &tmp->params().encoding();
477 tmp->makeLaTeXFile(writefile,
478 onlyPath(masterFilename(buffer)),
480 runparams.encoding = oldEnc;
482 // Copy the file to the temp dir, so that .aux files etc.
483 // are not created in the original dir. Files included by
484 // this file will be found via input@path, see ../Buffer.cpp.
485 unsigned long const checksum_in = sum(included_file);
486 unsigned long const checksum_out = sum(writefile);
488 if (checksum_in != checksum_out) {
489 if (!copy(included_file, writefile)) {
492 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
493 "into the temporary directory."),
494 from_utf8(included_file.absFilename())))
501 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
502 "latex" : "pdflatex";
503 if (isVerbatim(params_)) {
504 incfile = latex_path(incfile);
506 os << '\\' << from_ascii(params_.getCmdName()) << '{'
507 << from_utf8(incfile) << '}';
508 } else if (type(params_) == INPUT) {
509 runparams.exportdata->addExternalFile(tex_format, writefile,
512 // \input wants file with extension (default is .tex)
513 if (!isLyXFilename(included_file.absFilename())) {
514 incfile = latex_path(incfile);
516 os << '\\' << from_ascii(params_.getCmdName())
517 << '{' << from_utf8(incfile) << '}';
519 incfile = changeExtension(incfile, ".tex");
520 incfile = latex_path(incfile);
522 os << '\\' << from_ascii(params_.getCmdName())
523 << '{' << from_utf8(incfile) << '}';
525 } else if (type(params_) == LISTINGS) {
526 os << '\\' << from_ascii(params_.getCmdName());
527 string opt = params_.getOptions();
528 // opt is set in QInclude dialog and should have passed validation.
529 InsetListingsParams params(opt);
530 if (!params.params().empty())
531 os << "[" << from_utf8(params.encodedString()) << "]";
532 os << '{' << from_utf8(incfile) << '}';
534 runparams.exportdata->addExternalFile(tex_format, writefile,
537 // \include don't want extension and demands that the
538 // file really have .tex
539 incfile = changeExtension(incfile, string());
540 incfile = latex_path(incfile);
542 os << '\\' << from_ascii(params_.getCmdName()) << '{'
543 << from_utf8(incfile) << '}';
550 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
551 OutputParams const &) const
553 if (isVerbatim(params_) || isListings(params_)) {
554 os << '[' << getScreenLabel(buffer) << '\n';
555 // FIXME: We don't know the encoding of the file
556 docstring const str =
557 from_utf8(getFileContents(includedFilename(buffer, params_)));
560 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
562 docstring const str = '[' + getScreenLabel(buffer) + ']';
569 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
570 OutputParams const & runparams) const
572 string incfile = to_utf8(params_["filename"]);
574 // Do nothing if no file name has been specified
578 string const included_file = includedFilename(buffer, params_).absFilename();
580 //Check we're not trying to include ourselves.
581 //FIXME RECURSIVE INCLUDE
582 //This isn't sufficient, as the inclusion could be downstream.
583 //But it'll have to do for now.
584 if (buffer.fileName() == included_file) {
585 Alert::error(_("Recursive input"),
586 bformat(_("Attempted to include file %1$s in itself! "
587 "Ignoring inclusion."), from_utf8(incfile)));
591 // write it to a file (so far the complete file)
592 string const exportfile = changeExtension(incfile, ".sgml");
593 DocFileName writefile(changeExtension(included_file, ".sgml"));
595 if (loadIfNeeded(buffer, params_)) {
596 Buffer * tmp = theBufferList().getBuffer(included_file);
598 string const mangled = writefile.mangledFilename();
599 writefile = makeAbsPath(mangled,
600 buffer.getMasterBuffer()->temppath());
604 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
605 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
606 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
608 tmp->makeDocBookFile(writefile, runparams, true);
611 runparams.exportdata->addExternalFile("docbook", writefile,
613 runparams.exportdata->addExternalFile("docbook-xml", writefile,
616 if (isVerbatim(params_) || isListings(params_)) {
617 os << "<inlinegraphic fileref=\""
618 << '&' << include_label << ';'
619 << "\" format=\"linespecific\">";
621 os << '&' << include_label << ';';
627 void InsetInclude::validate(LaTeXFeatures & features) const
629 string incfile(to_utf8(params_["filename"]));
632 Buffer const & buffer = features.buffer();
634 string const included_file = includedFilename(buffer, params_).absFilename();
636 if (isLyXFilename(included_file))
637 writefile = changeExtension(included_file, ".sgml");
639 writefile = included_file;
641 if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
642 incfile = DocFileName(writefile).mangledFilename();
643 writefile = makeAbsPath(incfile,
644 buffer.getMasterBuffer()->temppath()).absFilename();
647 features.includeFile(include_label, writefile);
649 if (isVerbatim(params_))
650 features.require("verbatim");
651 else if (isListings(params_))
652 features.require("listings");
654 // Here we must do the fun stuff...
655 // Load the file in the include if it needs
657 if (loadIfNeeded(buffer, params_)) {
659 Buffer * const tmp = theBufferList().getBuffer(included_file);
660 // make sure the buffer isn't us
661 // FIXME RECURSIVE INCLUDES
662 // This is not sufficient, as recursive includes could be
663 // more than a file away. But it will do for now.
664 if (tmp && tmp != & buffer) {
665 // We must temporarily change features.buffer,
666 // otherwise it would always be the master buffer,
667 // and nested includes would not work.
668 features.setBuffer(*tmp);
669 tmp->validate(features);
670 features.setBuffer(buffer);
676 void InsetInclude::getLabelList(Buffer const & buffer,
677 std::vector<docstring> & list) const
679 if (isListings(params_)) {
680 InsetListingsParams params(params_.getOptions());
681 string label = params.getParamValue("label");
683 list.push_back(from_utf8(label));
685 else if (loadIfNeeded(buffer, params_)) {
686 string const included_file = includedFilename(buffer, params_).absFilename();
687 Buffer * tmp = theBufferList().getBuffer(included_file);
688 tmp->setParentName("");
689 tmp->getLabelList(list);
690 tmp->setParentName(parentFilename(buffer));
695 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
696 std::vector<std::pair<string, docstring> > & keys) const
698 if (loadIfNeeded(buffer, params_)) {
699 string const included_file = includedFilename(buffer, params_).absFilename();
700 Buffer * tmp = theBufferList().getBuffer(included_file);
701 tmp->setParentName("");
702 tmp->fillWithBibKeys(keys);
703 tmp->setParentName(parentFilename(buffer));
708 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
710 Buffer * const tmp = getChildBuffer(buffer, params_);
712 tmp->setParentName("");
713 tmp->updateBibfilesCache();
714 tmp->setParentName(parentFilename(buffer));
719 std::vector<FileName> const &
720 InsetInclude::getBibfilesCache(Buffer const & buffer) const
722 Buffer * const tmp = getChildBuffer(buffer, params_);
724 tmp->setParentName("");
725 std::vector<FileName> const & cache = tmp->getBibfilesCache();
726 tmp->setParentName(parentFilename(buffer));
729 static std::vector<FileName> const empty;
734 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
736 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
738 bool use_preview = false;
739 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
740 graphics::PreviewImage const * pimage =
741 preview_->getPreviewImage(*mi.base.bv->buffer());
742 use_preview = pimage && pimage->image();
746 preview_->metrics(mi, dim);
750 button_.update(getScreenLabel(*mi.base.bv->buffer()),
753 button_.metrics(mi, dim);
756 Box b(0, dim.wid, -dim.asc, dim.des);
759 bool const changed = dim_ != dim;
765 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
767 setPosCache(pi, x, y);
769 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
771 bool use_preview = false;
772 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
773 graphics::PreviewImage const * pimage =
774 preview_->getPreviewImage(*pi.base.bv->buffer());
775 use_preview = pimage && pimage->image();
779 preview_->draw(pi, x, y);
781 button_.draw(pi, x, y);
785 Inset::DisplayType InsetInclude::display() const
787 return type(params_) == INPUT ? Inline : AlignCenter;
796 void InsetInclude::fileChanged() const
798 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
802 Buffer const & buffer = *buffer_ptr;
803 preview_->removePreview(buffer);
804 add_preview(*preview_.get(), *this, buffer);
805 preview_->startLoading(buffer);
811 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
813 FileName const included_file = includedFilename(buffer, params);
815 return type(params) == INPUT && params.preview() &&
816 isFileReadable(included_file);
820 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
823 // We don't need to set runparams.encoding since this will be done
824 // by latex() anyway.
825 OutputParams runparams(0);
826 runparams.flavor = OutputParams::LATEX;
827 inset.latex(buffer, os, runparams);
833 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
834 Buffer const & buffer)
836 InsetCommandParams const & params = inset.params();
837 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
838 preview_wanted(params, buffer)) {
839 renderer.setAbsFile(includedFilename(buffer, params));
840 docstring const snippet = latex_string(inset, buffer);
841 renderer.addPreview(snippet, buffer);
848 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
850 Buffer const & buffer = ploader.buffer();
851 if (preview_wanted(params(), buffer)) {
852 preview_->setAbsFile(includedFilename(buffer, params()));
853 docstring const snippet = latex_string(*this, buffer);
854 preview_->addPreview(snippet, ploader);
859 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
861 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
865 TocList const & childtoclist = childbuffer->tocBackend().tocs();
866 TocList::const_iterator it = childtoclist.begin();
867 TocList::const_iterator const end = childtoclist.end();
868 for(; it != end; ++it)
869 toclist[it->first].insert(toclist[it->first].end(),
870 it->second.begin(), it->second.end());
874 void InsetInclude::updateLabels(Buffer const & buffer) const
876 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
880 lyx::updateLabels(*childbuffer, true);
884 string const InsetIncludeMailer::name_("include");
886 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
891 string const InsetIncludeMailer::inset2string(Buffer const &) const
893 return params2string(inset_.params());
897 void InsetIncludeMailer::string2params(string const & in,
898 InsetCommandParams & params)
904 istringstream data(in);
910 if (!lex || name != name_)
911 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
913 // This is part of the inset proper that is usually swallowed
914 // by Text::readInset
917 if (!lex || id != "Include")
918 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
920 InsetInclude inset(params);
922 params = inset.params();
927 InsetIncludeMailer::params2string(InsetCommandParams const & params)
929 InsetInclude inset(params);
931 data << name_ << ' ';
933 data << "\\end_inset\n";