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::isFileReadable;
66 using support::isLyXFilename;
67 using support::latex_path;
68 using support::makeAbsPath;
69 using support::makeDisplayPath;
70 using support::makeRelPath;
71 using support::onlyFilename;
72 using support::onlyPath;
79 using std::istringstream;
81 using std::ostringstream;
83 namespace Alert = frontend::Alert;
84 namespace fs = boost::filesystem;
89 docstring const uniqueID()
91 static unsigned int seed = 1000;
92 return "file" + convert<docstring>(++seed);
98 InsetInclude::InsetInclude(InsetCommandParams const & p)
99 : params_(p), include_label(uniqueID()),
100 preview_(new RenderMonitoredPreview(this)),
103 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
107 InsetInclude::InsetInclude(InsetInclude const & other)
109 params_(other.params_),
110 include_label(other.include_label),
111 preview_(new RenderMonitoredPreview(this)),
114 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
118 InsetInclude::~InsetInclude()
120 InsetIncludeMailer(*this).hideDialog();
124 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
126 switch (cmd.action) {
128 case LFUN_INSET_MODIFY: {
129 InsetCommandParams p("include");
130 InsetIncludeMailer::string2params(to_utf8(cmd.argument()), p);
131 if (!p.getCmdName().empty()) {
132 set(p, cur.buffer());
133 cur.buffer().updateBibfilesCache();
139 case LFUN_INSET_DIALOG_UPDATE:
140 InsetIncludeMailer(*this).updateDialog(&cur.bv());
143 case LFUN_MOUSE_RELEASE:
144 InsetIncludeMailer(*this).showDialog(&cur.bv());
148 Inset::doDispatch(cur, cmd);
154 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
155 FuncStatus & flag) const
157 switch (cmd.action) {
159 case LFUN_INSET_MODIFY:
160 case LFUN_INSET_DIALOG_UPDATE:
165 return Inset::getStatus(cur, cmd, flag);
170 InsetCommandParams const & InsetInclude::params() const
178 /// the type of inclusion
188 Types type(InsetCommandParams const & params)
190 string const command_name = params.getCmdName();
192 if (command_name == "input")
194 if (command_name == "verbatiminput")
196 if (command_name == "verbatiminput*")
198 if (command_name == "lstinputlisting")
204 bool isVerbatim(InsetCommandParams const & params)
206 string const command_name = params.getCmdName();
207 return command_name == "verbatiminput" ||
208 command_name == "verbatiminput*";
212 bool isListings(InsetCommandParams const & params)
214 return params.getCmdName() == "lstinputlisting";
218 string const masterFilename(Buffer const & buffer)
220 return buffer.getMasterBuffer()->fileName();
224 string const parentFilename(Buffer const & buffer)
226 return buffer.fileName();
230 FileName const includedFilename(Buffer const & buffer,
231 InsetCommandParams const & params)
233 return makeAbsPath(to_utf8(params["filename"]),
234 onlyPath(parentFilename(buffer)));
238 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
243 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
248 if (preview_->monitoring())
249 preview_->stopMonitoring();
251 if (type(params_) == INPUT)
252 add_preview(*preview_, *this, buffer);
256 auto_ptr<Inset> InsetInclude::doClone() const
258 return auto_ptr<Inset>(new InsetInclude(*this));
262 void InsetInclude::write(Buffer const &, ostream & os) const
268 void InsetInclude::write(ostream & os) const
270 os << "Include " << to_utf8(params_.getCommand()) << '\n'
271 << "preview " << convert<string>(params_.preview()) << '\n';
275 void InsetInclude::read(Buffer const &, Lexer & lex)
281 void InsetInclude::read(Lexer & lex)
285 string const command = lex.getString();
286 params_.scanCommand(command);
291 token = lex.getString();
292 if (token == "\\end_inset")
294 if (token == "preview") {
296 params_.preview(lex.getBool());
298 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
300 if (token != "\\end_inset") {
301 lex.printError("Missing \\end_inset at this point. "
307 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
311 switch (type(params_)) {
313 temp += buf.B_("Input");
316 temp += buf.B_("Verbatim Input");
319 temp += buf.B_("Verbatim Input*");
322 temp += buf.B_("Include");
325 temp += buf.B_("Program Listing");
331 if (params_["filename"].empty())
334 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
342 /// return the child buffer if the file is a LyX doc and is loaded
343 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
345 if (isVerbatim(params) || isListings(params))
348 string const included_file = includedFilename(buffer, params).absFilename();
349 if (!isLyXFilename(included_file))
352 return theBufferList().getBuffer(included_file);
356 /// return true if the file is or got loaded.
357 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
359 if (isVerbatim(params) || isListings(params))
362 FileName const included_file = includedFilename(buffer, params);
363 if (!isLyXFilename(included_file.absFilename()))
366 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
368 // the readonly flag can/will be wrong, not anymore I think.
369 if (!fs::exists(included_file.toFilesystemEncoding()))
371 buf = theBufferList().newBuffer(included_file.absFilename());
372 if (!loadLyXFile(buf, included_file))
376 buf->setParentName(parentFilename(buffer));
384 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
385 OutputParams const & runparams) const
387 string incfile(to_utf8(params_["filename"]));
389 // Do nothing if no file name has been specified
393 FileName const included_file(includedFilename(buffer, params_));
394 Buffer const * const m_buffer = buffer.getMasterBuffer();
396 // if incfile is relative, make it relative to the master
398 if (!absolutePath(incfile)) {
400 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
401 from_utf8(m_buffer->filePath())));
404 // write it to a file (so far the complete file)
405 string const exportfile = changeExtension(incfile, ".tex");
406 string const mangled = DocFileName(changeExtension(included_file.absFilename(),
407 ".tex")).mangledFilename();
408 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
412 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
413 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
414 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
416 if (runparams.inComment || runparams.dryrun)
417 // Don't try to load or copy the file
419 else if (loadIfNeeded(buffer, params_)) {
420 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
422 if (tmp->params().textclass != m_buffer->params().textclass) {
424 docstring text = bformat(_("Included file `%1$s'\n"
425 "has textclass `%2$s'\n"
426 "while parent file has textclass `%3$s'."),
427 makeDisplayPath(included_file.absFilename()),
428 from_utf8(tmp->params().getTextClass().name()),
429 from_utf8(m_buffer->params().getTextClass().name()));
430 Alert::warning(_("Different textclasses"), text);
434 tmp->markDepClean(m_buffer->temppath());
437 #warning handle non existing files
438 #warning Second argument is irrelevant!
439 // since only_body is true, makeLaTeXFile will not look at second
440 // argument. Should we set it to string(), or should makeLaTeXFile
441 // make use of it somehow? (JMarc 20031002)
443 // The included file might be written in a different encoding
444 Encoding const * const oldEnc = runparams.encoding;
445 runparams.encoding = &tmp->params().encoding();
446 tmp->makeLaTeXFile(writefile,
447 onlyPath(masterFilename(buffer)),
449 runparams.encoding = oldEnc;
451 // Copy the file to the temp dir, so that .aux files etc.
452 // are not created in the original dir. Files included by
453 // this file will be found via input@path, see ../Buffer.cpp.
454 unsigned long const checksum_in = sum(included_file);
455 unsigned long const checksum_out = sum(writefile);
457 if (checksum_in != checksum_out) {
458 if (!copy(included_file, writefile)) {
461 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
462 "into the temporary directory."),
463 from_utf8(included_file.absFilename())))
470 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
471 "latex" : "pdflatex";
472 if (isVerbatim(params_)) {
473 incfile = latex_path(incfile);
475 os << '\\' << from_ascii(params_.getCmdName()) << '{'
476 << from_utf8(incfile) << '}';
477 } else if (type(params_) == INPUT) {
478 runparams.exportdata->addExternalFile(tex_format, writefile,
481 // \input wants file with extension (default is .tex)
482 if (!isLyXFilename(included_file.absFilename())) {
483 incfile = latex_path(incfile);
485 os << '\\' << from_ascii(params_.getCmdName())
486 << '{' << from_utf8(incfile) << '}';
488 incfile = changeExtension(incfile, ".tex");
489 incfile = latex_path(incfile);
491 os << '\\' << from_ascii(params_.getCmdName())
492 << '{' << from_utf8(incfile) << '}';
494 } else if (type(params_) == LISTINGS) {
495 os << '\\' << from_ascii(params_.getCmdName());
496 string opt = params_.getOptions();
497 // opt is set in QInclude dialog and should have passed validation.
498 InsetListingsParams params(opt);
499 if (!params.params().empty())
500 os << "[" << from_utf8(params.encodedString()) << "]";
501 os << '{' << from_utf8(incfile) << '}';
503 runparams.exportdata->addExternalFile(tex_format, writefile,
506 // \include don't want extension and demands that the
507 // file really have .tex
508 incfile = changeExtension(incfile, string());
509 incfile = latex_path(incfile);
511 os << '\\' << from_ascii(params_.getCmdName()) << '{'
512 << from_utf8(incfile) << '}';
519 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
520 OutputParams const &) const
522 if (isVerbatim(params_) || isListings(params_)) {
523 os << '[' << getScreenLabel(buffer) << '\n';
524 // FIXME: We don't know the encoding of the file
525 docstring const str =
526 from_utf8(getFileContents(includedFilename(buffer, params_)));
529 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
531 docstring const str = '[' + getScreenLabel(buffer) + ']';
538 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
539 OutputParams const & runparams) const
541 string incfile = to_utf8(params_["filename"]);
543 // Do nothing if no file name has been specified
547 string const included_file = includedFilename(buffer, params_).absFilename();
549 // write it to a file (so far the complete file)
550 string const exportfile = changeExtension(incfile, ".sgml");
551 DocFileName writefile(changeExtension(included_file, ".sgml"));
553 if (loadIfNeeded(buffer, params_)) {
554 Buffer * tmp = theBufferList().getBuffer(included_file);
556 string const mangled = writefile.mangledFilename();
557 writefile = makeAbsPath(mangled,
558 buffer.getMasterBuffer()->temppath());
562 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
563 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
564 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
566 tmp->makeDocBookFile(writefile, runparams, true);
569 runparams.exportdata->addExternalFile("docbook", writefile,
571 runparams.exportdata->addExternalFile("docbook-xml", writefile,
574 if (isVerbatim(params_) || isListings(params_)) {
575 os << "<inlinegraphic fileref=\""
576 << '&' << include_label << ';'
577 << "\" format=\"linespecific\">";
579 os << '&' << include_label << ';';
585 void InsetInclude::validate(LaTeXFeatures & features) const
587 string incfile(to_utf8(params_["filename"]));
590 Buffer const & buffer = features.buffer();
592 string const included_file = includedFilename(buffer, params_).absFilename();
594 if (isLyXFilename(included_file))
595 writefile = changeExtension(included_file, ".sgml");
597 writefile = included_file;
599 if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
600 incfile = DocFileName(writefile).mangledFilename();
601 writefile = makeAbsPath(incfile,
602 buffer.getMasterBuffer()->temppath()).absFilename();
605 features.includeFile(include_label, writefile);
607 if (isVerbatim(params_))
608 features.require("verbatim");
609 else if (isListings(params_))
610 features.require("listings");
612 // Here we must do the fun stuff...
613 // Load the file in the include if it needs
615 if (loadIfNeeded(buffer, params_)) {
617 Buffer * const tmp = theBufferList().getBuffer(included_file);
619 // We must temporarily change features.buffer,
620 // otherwise it would always be the master buffer,
621 // and nested includes would not work.
622 features.setBuffer(*tmp);
623 tmp->validate(features);
624 features.setBuffer(buffer);
630 void InsetInclude::getLabelList(Buffer const & buffer,
631 std::vector<docstring> & list) const
633 if (loadIfNeeded(buffer, params_)) {
634 string const included_file = includedFilename(buffer, params_).absFilename();
635 Buffer * tmp = theBufferList().getBuffer(included_file);
636 tmp->setParentName("");
637 tmp->getLabelList(list);
638 tmp->setParentName(parentFilename(buffer));
643 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
644 std::vector<std::pair<string, docstring> > & keys) const
646 if (loadIfNeeded(buffer, params_)) {
647 string const included_file = includedFilename(buffer, params_).absFilename();
648 Buffer * tmp = theBufferList().getBuffer(included_file);
649 tmp->setParentName("");
650 tmp->fillWithBibKeys(keys);
651 tmp->setParentName(parentFilename(buffer));
656 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
658 Buffer * const tmp = getChildBuffer(buffer, params_);
660 tmp->setParentName("");
661 tmp->updateBibfilesCache();
662 tmp->setParentName(parentFilename(buffer));
667 std::vector<FileName> const &
668 InsetInclude::getBibfilesCache(Buffer const & buffer) const
670 Buffer * const tmp = getChildBuffer(buffer, params_);
672 tmp->setParentName("");
673 std::vector<FileName> const & cache = tmp->getBibfilesCache();
674 tmp->setParentName(parentFilename(buffer));
677 static std::vector<FileName> const empty;
682 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
684 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
686 bool use_preview = false;
687 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
688 graphics::PreviewImage const * pimage =
689 preview_->getPreviewImage(*mi.base.bv->buffer());
690 use_preview = pimage && pimage->image();
694 preview_->metrics(mi, dim);
698 button_.update(getScreenLabel(*mi.base.bv->buffer()),
701 button_.metrics(mi, dim);
704 Box b(0, dim.wid, -dim.asc, dim.des);
707 bool const changed = dim_ != dim;
713 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
715 setPosCache(pi, x, y);
717 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
719 bool use_preview = false;
720 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
721 graphics::PreviewImage const * pimage =
722 preview_->getPreviewImage(*pi.base.bv->buffer());
723 use_preview = pimage && pimage->image();
727 preview_->draw(pi, x, y);
729 button_.draw(pi, x, y);
732 bool InsetInclude::display() const
734 return type(params_) != INPUT;
743 void InsetInclude::fileChanged() const
745 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
749 Buffer const & buffer = *buffer_ptr;
750 preview_->removePreview(buffer);
751 add_preview(*preview_.get(), *this, buffer);
752 preview_->startLoading(buffer);
758 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
760 FileName const included_file = includedFilename(buffer, params);
762 return type(params) == INPUT && params.preview() &&
763 isFileReadable(included_file);
767 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
770 // We don't need to set runparams.encoding since this will be done
771 // by latex() anyway.
772 OutputParams runparams(0);
773 runparams.flavor = OutputParams::LATEX;
774 inset.latex(buffer, os, runparams);
780 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
781 Buffer const & buffer)
783 InsetCommandParams const & params = inset.params();
784 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
785 preview_wanted(params, buffer)) {
786 renderer.setAbsFile(includedFilename(buffer, params));
787 docstring const snippet = latex_string(inset, buffer);
788 renderer.addPreview(snippet, buffer);
795 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
797 Buffer const & buffer = ploader.buffer();
798 if (preview_wanted(params(), buffer)) {
799 preview_->setAbsFile(includedFilename(buffer, params()));
800 docstring const snippet = latex_string(*this, buffer);
801 preview_->addPreview(snippet, ploader);
806 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
808 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
812 TocList const & childtoclist = childbuffer->tocBackend().tocs();
813 TocList::const_iterator it = childtoclist.begin();
814 TocList::const_iterator const end = childtoclist.end();
815 for(; it != end; ++it)
816 toclist[it->first].insert(toclist[it->first].end(),
817 it->second.begin(), it->second.end());
821 void InsetInclude::updateLabels(Buffer const & buffer) const
823 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
827 lyx::updateLabels(*childbuffer, true);
831 string const InsetIncludeMailer::name_("include");
833 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
838 string const InsetIncludeMailer::inset2string(Buffer const &) const
840 return params2string(inset_.params());
844 void InsetIncludeMailer::string2params(string const & in,
845 InsetCommandParams & params)
851 istringstream data(in);
857 if (!lex || name != name_)
858 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
860 // This is part of the inset proper that is usually swallowed
861 // by Text::readInset
864 if (!lex || id != "Include")
865 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
867 InsetInclude inset(params);
869 params = inset.params();
874 InsetIncludeMailer::params2string(InsetCommandParams const & params)
876 InsetInclude inset(params);
878 data << name_ << ' ';
880 data << "\\end_inset\n";