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 return theBufferList().getBuffer(included_file);
370 /// return true if the file is or got loaded.
371 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
373 if (isVerbatim(params) || isListings(params))
376 FileName const included_file = includedFilename(buffer, params);
377 if (!isLyXFilename(included_file.absFilename()))
380 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
382 // the readonly flag can/will be wrong, not anymore I think.
383 if (!fs::exists(included_file.toFilesystemEncoding()))
385 buf = theBufferList().newBuffer(included_file.absFilename());
386 if (!loadLyXFile(buf, included_file))
390 buf->setParentName(parentFilename(buffer));
398 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
399 OutputParams const & runparams) const
401 string incfile(to_utf8(params_["filename"]));
403 // Do nothing if no file name has been specified
407 FileName const included_file(includedFilename(buffer, params_));
408 Buffer const * const m_buffer = buffer.getMasterBuffer();
410 // if incfile is relative, make it relative to the master
412 if (!absolutePath(incfile)) {
414 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
415 from_utf8(m_buffer->filePath())));
418 // write it to a file (so far the complete file)
419 string const exportfile = changeExtension(incfile, ".tex");
420 string const mangled = DocFileName(changeExtension(included_file.absFilename(),
421 ".tex")).mangledFilename();
422 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
426 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
427 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
428 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
430 if (runparams.inComment || runparams.dryrun)
431 // Don't try to load or copy the file
433 else if (loadIfNeeded(buffer, params_)) {
434 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
436 if (tmp->params().textclass != m_buffer->params().textclass) {
438 docstring text = bformat(_("Included file `%1$s'\n"
439 "has textclass `%2$s'\n"
440 "while parent file has textclass `%3$s'."),
441 makeDisplayPath(included_file.absFilename()),
442 from_utf8(tmp->params().getTextClass().name()),
443 from_utf8(m_buffer->params().getTextClass().name()));
444 Alert::warning(_("Different textclasses"), text);
448 tmp->markDepClean(m_buffer->temppath());
451 #warning handle non existing files
452 #warning Second argument is irrelevant!
453 // since only_body is true, makeLaTeXFile will not look at second
454 // argument. Should we set it to string(), or should makeLaTeXFile
455 // make use of it somehow? (JMarc 20031002)
457 // The included file might be written in a different encoding
458 Encoding const * const oldEnc = runparams.encoding;
459 runparams.encoding = &tmp->params().encoding();
460 tmp->makeLaTeXFile(writefile,
461 onlyPath(masterFilename(buffer)),
463 runparams.encoding = oldEnc;
465 // Copy the file to the temp dir, so that .aux files etc.
466 // are not created in the original dir. Files included by
467 // this file will be found via input@path, see ../Buffer.cpp.
468 unsigned long const checksum_in = sum(included_file);
469 unsigned long const checksum_out = sum(writefile);
471 if (checksum_in != checksum_out) {
472 if (!copy(included_file, writefile)) {
475 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
476 "into the temporary directory."),
477 from_utf8(included_file.absFilename())))
484 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
485 "latex" : "pdflatex";
486 if (isVerbatim(params_)) {
487 incfile = latex_path(incfile);
489 os << '\\' << from_ascii(params_.getCmdName()) << '{'
490 << from_utf8(incfile) << '}';
491 } else if (type(params_) == INPUT) {
492 runparams.exportdata->addExternalFile(tex_format, writefile,
495 // \input wants file with extension (default is .tex)
496 if (!isLyXFilename(included_file.absFilename())) {
497 incfile = latex_path(incfile);
499 os << '\\' << from_ascii(params_.getCmdName())
500 << '{' << from_utf8(incfile) << '}';
502 incfile = changeExtension(incfile, ".tex");
503 incfile = latex_path(incfile);
505 os << '\\' << from_ascii(params_.getCmdName())
506 << '{' << from_utf8(incfile) << '}';
508 } else if (type(params_) == LISTINGS) {
509 os << '\\' << from_ascii(params_.getCmdName());
510 string opt = params_.getOptions();
511 // opt is set in QInclude dialog and should have passed validation.
512 InsetListingsParams params(opt);
513 if (!params.params().empty())
514 os << "[" << from_utf8(params.encodedString()) << "]";
515 os << '{' << from_utf8(incfile) << '}';
517 runparams.exportdata->addExternalFile(tex_format, writefile,
520 // \include don't want extension and demands that the
521 // file really have .tex
522 incfile = changeExtension(incfile, string());
523 incfile = latex_path(incfile);
525 os << '\\' << from_ascii(params_.getCmdName()) << '{'
526 << from_utf8(incfile) << '}';
533 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
534 OutputParams const &) const
536 if (isVerbatim(params_) || isListings(params_)) {
537 os << '[' << getScreenLabel(buffer) << '\n';
538 // FIXME: We don't know the encoding of the file
539 docstring const str =
540 from_utf8(getFileContents(includedFilename(buffer, params_)));
543 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
545 docstring const str = '[' + getScreenLabel(buffer) + ']';
552 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
553 OutputParams const & runparams) const
555 string incfile = to_utf8(params_["filename"]);
557 // Do nothing if no file name has been specified
561 string const included_file = includedFilename(buffer, params_).absFilename();
563 // write it to a file (so far the complete file)
564 string const exportfile = changeExtension(incfile, ".sgml");
565 DocFileName writefile(changeExtension(included_file, ".sgml"));
567 if (loadIfNeeded(buffer, params_)) {
568 Buffer * tmp = theBufferList().getBuffer(included_file);
570 string const mangled = writefile.mangledFilename();
571 writefile = makeAbsPath(mangled,
572 buffer.getMasterBuffer()->temppath());
576 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
577 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
578 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
580 tmp->makeDocBookFile(writefile, runparams, true);
583 runparams.exportdata->addExternalFile("docbook", writefile,
585 runparams.exportdata->addExternalFile("docbook-xml", writefile,
588 if (isVerbatim(params_) || isListings(params_)) {
589 os << "<inlinegraphic fileref=\""
590 << '&' << include_label << ';'
591 << "\" format=\"linespecific\">";
593 os << '&' << include_label << ';';
599 void InsetInclude::validate(LaTeXFeatures & features) const
601 string incfile(to_utf8(params_["filename"]));
604 Buffer const & buffer = features.buffer();
606 string const included_file = includedFilename(buffer, params_).absFilename();
608 if (isLyXFilename(included_file))
609 writefile = changeExtension(included_file, ".sgml");
611 writefile = included_file;
613 if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
614 incfile = DocFileName(writefile).mangledFilename();
615 writefile = makeAbsPath(incfile,
616 buffer.getMasterBuffer()->temppath()).absFilename();
619 features.includeFile(include_label, writefile);
621 if (isVerbatim(params_))
622 features.require("verbatim");
623 else if (isListings(params_))
624 features.require("listings");
626 // Here we must do the fun stuff...
627 // Load the file in the include if it needs
629 if (loadIfNeeded(buffer, params_)) {
631 Buffer * const tmp = theBufferList().getBuffer(included_file);
633 // We must temporarily change features.buffer,
634 // otherwise it would always be the master buffer,
635 // and nested includes would not work.
636 features.setBuffer(*tmp);
637 tmp->validate(features);
638 features.setBuffer(buffer);
644 void InsetInclude::getLabelList(Buffer const & buffer,
645 std::vector<docstring> & list) const
647 if (isListings(params_)) {
648 InsetListingsParams params(params_.getOptions());
649 string label = params.getParamValue("label");
651 list.push_back(from_utf8(label));
653 else if (loadIfNeeded(buffer, params_)) {
654 string const included_file = includedFilename(buffer, params_).absFilename();
655 Buffer * tmp = theBufferList().getBuffer(included_file);
656 tmp->setParentName("");
657 tmp->getLabelList(list);
658 tmp->setParentName(parentFilename(buffer));
663 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
664 std::vector<std::pair<string, docstring> > & keys) const
666 if (loadIfNeeded(buffer, params_)) {
667 string const included_file = includedFilename(buffer, params_).absFilename();
668 Buffer * tmp = theBufferList().getBuffer(included_file);
669 tmp->setParentName("");
670 tmp->fillWithBibKeys(keys);
671 tmp->setParentName(parentFilename(buffer));
676 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
678 Buffer * const tmp = getChildBuffer(buffer, params_);
680 tmp->setParentName("");
681 tmp->updateBibfilesCache();
682 tmp->setParentName(parentFilename(buffer));
687 std::vector<FileName> const &
688 InsetInclude::getBibfilesCache(Buffer const & buffer) const
690 Buffer * const tmp = getChildBuffer(buffer, params_);
692 tmp->setParentName("");
693 std::vector<FileName> const & cache = tmp->getBibfilesCache();
694 tmp->setParentName(parentFilename(buffer));
697 static std::vector<FileName> const empty;
702 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
704 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
706 bool use_preview = false;
707 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
708 graphics::PreviewImage const * pimage =
709 preview_->getPreviewImage(*mi.base.bv->buffer());
710 use_preview = pimage && pimage->image();
714 preview_->metrics(mi, dim);
718 button_.update(getScreenLabel(*mi.base.bv->buffer()),
721 button_.metrics(mi, dim);
724 Box b(0, dim.wid, -dim.asc, dim.des);
727 bool const changed = dim_ != dim;
733 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
735 setPosCache(pi, x, y);
737 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
739 bool use_preview = false;
740 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
741 graphics::PreviewImage const * pimage =
742 preview_->getPreviewImage(*pi.base.bv->buffer());
743 use_preview = pimage && pimage->image();
747 preview_->draw(pi, x, y);
749 button_.draw(pi, x, y);
753 Inset::DisplayType InsetInclude::display() const
755 return type(params_) == INPUT ? Inline : AlignCenter;
764 void InsetInclude::fileChanged() const
766 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
770 Buffer const & buffer = *buffer_ptr;
771 preview_->removePreview(buffer);
772 add_preview(*preview_.get(), *this, buffer);
773 preview_->startLoading(buffer);
779 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
781 FileName const included_file = includedFilename(buffer, params);
783 return type(params) == INPUT && params.preview() &&
784 isFileReadable(included_file);
788 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
791 // We don't need to set runparams.encoding since this will be done
792 // by latex() anyway.
793 OutputParams runparams(0);
794 runparams.flavor = OutputParams::LATEX;
795 inset.latex(buffer, os, runparams);
801 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
802 Buffer const & buffer)
804 InsetCommandParams const & params = inset.params();
805 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
806 preview_wanted(params, buffer)) {
807 renderer.setAbsFile(includedFilename(buffer, params));
808 docstring const snippet = latex_string(inset, buffer);
809 renderer.addPreview(snippet, buffer);
816 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
818 Buffer const & buffer = ploader.buffer();
819 if (preview_wanted(params(), buffer)) {
820 preview_->setAbsFile(includedFilename(buffer, params()));
821 docstring const snippet = latex_string(*this, buffer);
822 preview_->addPreview(snippet, ploader);
827 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
829 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
833 TocList const & childtoclist = childbuffer->tocBackend().tocs();
834 TocList::const_iterator it = childtoclist.begin();
835 TocList::const_iterator const end = childtoclist.end();
836 for(; it != end; ++it)
837 toclist[it->first].insert(toclist[it->first].end(),
838 it->second.begin(), it->second.end());
842 void InsetInclude::updateLabels(Buffer const & buffer) const
844 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
848 lyx::updateLabels(*childbuffer, true);
852 string const InsetIncludeMailer::name_("include");
854 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
859 string const InsetIncludeMailer::inset2string(Buffer const &) const
861 return params2string(inset_.params());
865 void InsetIncludeMailer::string2params(string const & in,
866 InsetCommandParams & params)
872 istringstream data(in);
878 if (!lex || name != name_)
879 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
881 // This is part of the inset proper that is usually swallowed
882 // by Text::readInset
885 if (!lex || id != "Include")
886 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
888 InsetInclude inset(params);
890 params = inset.params();
895 InsetIncludeMailer::params2string(InsetCommandParams const & params)
897 InsetInclude inset(params);
899 data << name_ << ' ';
901 data << "\\end_inset\n";