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"
43 #include "support/filetools.h"
44 #include "support/lstrings.h" // contains
45 #include "support/lyxalgo.h"
46 #include "support/lyxlib.h"
47 #include "support/convert.h"
49 #include <boost/bind.hpp>
50 #include <boost/filesystem/operations.hpp>
55 using support::addName;
56 using support::absolutePath;
57 using support::bformat;
58 using support::changeExtension;
59 using support::contains;
61 using support::DocFileName;
62 using support::FileName;
63 using support::getFileContents;
64 using support::isFileReadable;
65 using support::isLyXFilename;
66 using support::latex_path;
67 using support::makeAbsPath;
68 using support::makeDisplayPath;
69 using support::makeRelPath;
70 using support::onlyFilename;
71 using support::onlyPath;
78 using std::istringstream;
80 using std::ostringstream;
82 namespace Alert = frontend::Alert;
83 namespace fs = boost::filesystem;
88 docstring const uniqueID()
90 static unsigned int seed = 1000;
91 return "file" + convert<docstring>(++seed);
97 InsetInclude::InsetInclude(InsetCommandParams const & p)
98 : params_(p), include_label(uniqueID()),
99 preview_(new RenderMonitoredPreview(this)),
102 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
106 InsetInclude::InsetInclude(InsetInclude const & other)
108 params_(other.params_),
109 include_label(other.include_label),
110 preview_(new RenderMonitoredPreview(this)),
113 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
117 InsetInclude::~InsetInclude()
119 InsetIncludeMailer(*this).hideDialog();
123 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
125 switch (cmd.action) {
127 case LFUN_INSET_MODIFY: {
128 InsetCommandParams p("include");
129 InsetIncludeMailer::string2params(to_utf8(cmd.argument()), p);
130 if (!p.getCmdName().empty()) {
131 set(p, cur.buffer());
132 cur.buffer().updateBibfilesCache();
138 case LFUN_INSET_DIALOG_UPDATE:
139 InsetIncludeMailer(*this).updateDialog(&cur.bv());
142 case LFUN_MOUSE_RELEASE:
143 InsetIncludeMailer(*this).showDialog(&cur.bv());
147 InsetBase::doDispatch(cur, cmd);
153 bool InsetInclude::getStatus(LCursor & cur, FuncRequest const & cmd,
154 FuncStatus & flag) const
156 switch (cmd.action) {
158 case LFUN_INSET_MODIFY:
159 case LFUN_INSET_DIALOG_UPDATE:
164 return InsetBase::getStatus(cur, cmd, flag);
169 InsetCommandParams const & InsetInclude::params() const
177 /// the type of inclusion
186 Types type(InsetCommandParams const & params)
188 string const command_name = params.getCmdName();
190 if (command_name == "input")
192 if (command_name == "verbatiminput")
194 if (command_name == "verbatiminput*")
200 bool isVerbatim(InsetCommandParams const & params)
202 string const command_name = params.getCmdName();
203 return command_name == "verbatiminput" ||
204 command_name == "verbatiminput*";
208 string const masterFilename(Buffer const & buffer)
210 return buffer.getMasterBuffer()->fileName();
214 string const parentFilename(Buffer const & buffer)
216 return buffer.fileName();
220 FileName const includedFilename(Buffer const & buffer,
221 InsetCommandParams const & params)
223 return makeAbsPath(to_utf8(params["filename"]),
224 onlyPath(parentFilename(buffer)));
228 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
233 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
238 if (preview_->monitoring())
239 preview_->stopMonitoring();
241 if (type(params_) == INPUT)
242 add_preview(*preview_, *this, buffer);
246 auto_ptr<InsetBase> InsetInclude::doClone() const
248 return auto_ptr<InsetBase>(new InsetInclude(*this));
252 void InsetInclude::write(Buffer const &, ostream & os) const
258 void InsetInclude::write(ostream & os) const
260 os << "Include " << to_utf8(params_.getCommand()) << '\n'
261 << "preview " << convert<string>(params_.preview()) << '\n';
265 void InsetInclude::read(Buffer const &, Lexer & lex)
271 void InsetInclude::read(Lexer & lex)
275 string const command = lex.getString();
276 params_.scanCommand(command);
281 token = lex.getString();
282 if (token == "\\end_inset")
284 if (token == "preview") {
286 params_.preview(lex.getBool());
288 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
290 if (token != "\\end_inset") {
291 lex.printError("Missing \\end_inset at this point. "
297 docstring const InsetInclude::getScreenLabel(Buffer const &) const
301 switch (type(params_)) {
306 temp += _("Verbatim Input");
309 temp += _("Verbatim Input*");
312 temp += _("Include");
318 if (params_["filename"].empty())
321 temp += from_utf8(onlyFilename(to_utf8(params_["filename"])));
329 /// return the child buffer if the file is a LyX doc and is loaded
330 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
332 if (isVerbatim(params))
335 string const included_file = includedFilename(buffer, params).absFilename();
336 if (!isLyXFilename(included_file))
339 return theBufferList().getBuffer(included_file);
343 /// return true if the file is or got loaded.
344 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
346 if (isVerbatim(params))
349 FileName const included_file = includedFilename(buffer, params);
350 if (!isLyXFilename(included_file.absFilename()))
353 Buffer * buf = theBufferList().getBuffer(included_file.absFilename());
355 // the readonly flag can/will be wrong, not anymore I think.
356 if (!fs::exists(included_file.toFilesystemEncoding()))
358 buf = theBufferList().newBuffer(included_file.absFilename());
359 if (!loadLyXFile(buf, included_file))
363 buf->setParentName(parentFilename(buffer));
371 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
372 OutputParams const & runparams) const
374 string incfile(to_utf8(params_["filename"]));
376 // Do nothing if no file name has been specified
380 FileName const included_file(includedFilename(buffer, params_));
381 Buffer const * const m_buffer = buffer.getMasterBuffer();
383 // if incfile is relative, make it relative to the master
385 if (!absolutePath(incfile)) {
387 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
388 from_utf8(m_buffer->filePath())));
391 // write it to a file (so far the complete file)
392 string const exportfile = changeExtension(incfile, ".tex");
393 string const mangled = DocFileName(changeExtension(included_file.absFilename(),
394 ".tex")).mangledFilename();
395 FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
399 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
400 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
401 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
403 if (runparams.inComment || runparams.dryrun)
404 // Don't try to load or copy the file
406 else if (loadIfNeeded(buffer, params_)) {
407 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
409 if (tmp->params().textclass != m_buffer->params().textclass) {
411 docstring text = bformat(_("Included file `%1$s'\n"
412 "has textclass `%2$s'\n"
413 "while parent file has textclass `%3$s'."),
414 makeDisplayPath(included_file.absFilename()),
415 from_utf8(tmp->params().getLyXTextClass().name()),
416 from_utf8(m_buffer->params().getLyXTextClass().name()));
417 Alert::warning(_("Different textclasses"), text);
421 tmp->markDepClean(m_buffer->temppath());
424 #warning handle non existing files
425 #warning Second argument is irrelevant!
426 // since only_body is true, makeLaTeXFile will not look at second
427 // argument. Should we set it to string(), or should makeLaTeXFile
428 // make use of it somehow? (JMarc 20031002)
430 // The included file might be written in a different encoding
431 Encoding const * const oldEnc = runparams.encoding;
432 runparams.encoding = &tmp->params().encoding();
433 tmp->makeLaTeXFile(writefile,
434 onlyPath(masterFilename(buffer)),
436 runparams.encoding = oldEnc;
438 // Copy the file to the temp dir, so that .aux files etc.
439 // are not created in the original dir. Files included by
440 // this file will be found via input@path, see ../Buffer.cpp.
441 unsigned long const checksum_in = sum(included_file);
442 unsigned long const checksum_out = sum(writefile);
444 if (checksum_in != checksum_out) {
445 if (!copy(included_file, writefile)) {
448 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
449 "into the temporary directory."),
450 from_utf8(included_file.absFilename())))
457 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
458 "latex" : "pdflatex";
459 if (isVerbatim(params_)) {
460 incfile = latex_path(incfile);
462 os << '\\' << from_ascii(params_.getCmdName()) << '{'
463 << from_utf8(incfile) << '}';
464 } else if (type(params_) == INPUT) {
465 runparams.exportdata->addExternalFile(tex_format, writefile,
468 // \input wants file with extension (default is .tex)
469 if (!isLyXFilename(included_file.absFilename())) {
470 incfile = latex_path(incfile);
472 os << '\\' << from_ascii(params_.getCmdName())
473 << '{' << from_utf8(incfile) << '}';
475 incfile = changeExtension(incfile, ".tex");
476 incfile = latex_path(incfile);
478 os << '\\' << from_ascii(params_.getCmdName())
479 << '{' << from_utf8(incfile) << '}';
482 runparams.exportdata->addExternalFile(tex_format, writefile,
485 // \include don't want extension and demands that the
486 // file really have .tex
487 incfile = changeExtension(incfile, string());
488 incfile = latex_path(incfile);
490 os << '\\' << from_ascii(params_.getCmdName()) << '{'
491 << from_utf8(incfile) << '}';
498 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
499 OutputParams const &) const
501 if (isVerbatim(params_)) {
502 os << '[' << getScreenLabel(buffer) << '\n';
503 // FIXME: We don't know the encoding of the file
504 docstring const str =
505 from_utf8(getFileContents(includedFilename(buffer, params_)));
508 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
510 docstring const str = '[' + getScreenLabel(buffer) + ']';
517 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
518 OutputParams const & runparams) const
520 string incfile = to_utf8(params_["filename"]);
522 // Do nothing if no file name has been specified
526 string const included_file = includedFilename(buffer, params_).absFilename();
528 // write it to a file (so far the complete file)
529 string const exportfile = changeExtension(incfile, ".sgml");
530 DocFileName writefile(changeExtension(included_file, ".sgml"));
532 if (loadIfNeeded(buffer, params_)) {
533 Buffer * tmp = theBufferList().getBuffer(included_file);
535 string const mangled = writefile.mangledFilename();
536 writefile = makeAbsPath(mangled,
537 buffer.getMasterBuffer()->temppath());
541 LYXERR(Debug::LATEX) << "incfile:" << incfile << endl;
542 LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
543 LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
545 tmp->makeDocBookFile(writefile, runparams, true);
548 runparams.exportdata->addExternalFile("docbook", writefile,
550 runparams.exportdata->addExternalFile("docbook-xml", writefile,
553 if (isVerbatim(params_)) {
554 os << "<inlinegraphic fileref=\""
555 << '&' << include_label << ';'
556 << "\" format=\"linespecific\">";
558 os << '&' << include_label << ';';
564 void InsetInclude::validate(LaTeXFeatures & features) const
566 string incfile(to_utf8(params_["filename"]));
569 Buffer const & buffer = features.buffer();
571 string const included_file = includedFilename(buffer, params_).absFilename();
573 if (isLyXFilename(included_file))
574 writefile = changeExtension(included_file, ".sgml");
576 writefile = included_file;
578 if (!features.runparams().nice && !isVerbatim(params_)) {
579 incfile = DocFileName(writefile).mangledFilename();
580 writefile = makeAbsPath(incfile,
581 buffer.getMasterBuffer()->temppath()).absFilename();
584 features.includeFile(include_label, writefile);
586 if (isVerbatim(params_))
587 features.require("verbatim");
589 // Here we must do the fun stuff...
590 // Load the file in the include if it needs
592 if (loadIfNeeded(buffer, params_)) {
594 Buffer * const tmp = theBufferList().getBuffer(included_file);
596 // We must temporarily change features.buffer,
597 // otherwise it would always be the master buffer,
598 // and nested includes would not work.
599 features.setBuffer(*tmp);
600 tmp->validate(features);
601 features.setBuffer(buffer);
607 void InsetInclude::getLabelList(Buffer const & buffer,
608 std::vector<docstring> & list) const
610 if (loadIfNeeded(buffer, params_)) {
611 string const included_file = includedFilename(buffer, params_).absFilename();
612 Buffer * tmp = theBufferList().getBuffer(included_file);
613 tmp->setParentName("");
614 tmp->getLabelList(list);
615 tmp->setParentName(parentFilename(buffer));
620 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
621 std::vector<std::pair<string, docstring> > & keys) const
623 if (loadIfNeeded(buffer, params_)) {
624 string const included_file = includedFilename(buffer, params_).absFilename();
625 Buffer * tmp = theBufferList().getBuffer(included_file);
626 tmp->setParentName("");
627 tmp->fillWithBibKeys(keys);
628 tmp->setParentName(parentFilename(buffer));
633 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
635 Buffer * const tmp = getChildBuffer(buffer, params_);
637 tmp->setParentName("");
638 tmp->updateBibfilesCache();
639 tmp->setParentName(parentFilename(buffer));
644 std::vector<FileName> const &
645 InsetInclude::getBibfilesCache(Buffer const & buffer) const
647 Buffer * const tmp = getChildBuffer(buffer, params_);
649 tmp->setParentName("");
650 std::vector<FileName> const & cache = tmp->getBibfilesCache();
651 tmp->setParentName(parentFilename(buffer));
654 static std::vector<FileName> const empty;
659 bool InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
661 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
663 bool use_preview = false;
664 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
665 graphics::PreviewImage const * pimage =
666 preview_->getPreviewImage(*mi.base.bv->buffer());
667 use_preview = pimage && pimage->image();
671 preview_->metrics(mi, dim);
675 button_.update(getScreenLabel(*mi.base.bv->buffer()),
678 button_.metrics(mi, dim);
681 Box b(0, dim.wid, -dim.asc, dim.des);
684 bool const changed = dim_ != dim;
690 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
692 setPosCache(pi, x, y);
694 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
696 bool use_preview = false;
697 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
698 graphics::PreviewImage const * pimage =
699 preview_->getPreviewImage(*pi.base.bv->buffer());
700 use_preview = pimage && pimage->image();
704 preview_->draw(pi, x, y);
706 button_.draw(pi, x, y);
709 bool InsetInclude::display() const
711 return type(params_) != INPUT;
720 void InsetInclude::fileChanged() const
722 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
726 Buffer const & buffer = *buffer_ptr;
727 preview_->removePreview(buffer);
728 add_preview(*preview_.get(), *this, buffer);
729 preview_->startLoading(buffer);
735 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
737 FileName const included_file = includedFilename(buffer, params);
739 return type(params) == INPUT && params.preview() &&
740 isFileReadable(included_file);
744 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
747 // We don't need to set runparams.encoding since this will be done
748 // by latex() anyway.
749 OutputParams runparams(0);
750 runparams.flavor = OutputParams::LATEX;
751 inset.latex(buffer, os, runparams);
757 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
758 Buffer const & buffer)
760 InsetCommandParams const & params = inset.params();
761 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
762 preview_wanted(params, buffer)) {
763 renderer.setAbsFile(includedFilename(buffer, params));
764 docstring const snippet = latex_string(inset, buffer);
765 renderer.addPreview(snippet, buffer);
772 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
774 Buffer const & buffer = ploader.buffer();
775 if (preview_wanted(params(), buffer)) {
776 preview_->setAbsFile(includedFilename(buffer, params()));
777 docstring const snippet = latex_string(*this, buffer);
778 preview_->addPreview(snippet, ploader);
783 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer) const
785 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
789 TocList const & childtoclist = childbuffer->tocBackend().tocs();
790 TocList::const_iterator it = childtoclist.begin();
791 TocList::const_iterator const end = childtoclist.end();
792 for(; it != end; ++it)
793 toclist[it->first].insert(toclist[it->first].end(),
794 it->second.begin(), it->second.end());
798 void InsetInclude::updateLabels(Buffer const & buffer) const
800 Buffer const * const childbuffer = getChildBuffer(buffer, params_);
804 lyx::updateLabels(*childbuffer, true);
808 string const InsetIncludeMailer::name_("include");
810 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
815 string const InsetIncludeMailer::inset2string(Buffer const &) const
817 return params2string(inset_.params());
821 void InsetIncludeMailer::string2params(string const & in,
822 InsetCommandParams & params)
828 istringstream data(in);
834 if (!lex || name != name_)
835 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
837 // This is part of the inset proper that is usually swallowed
838 // by LyXText::readInset
841 if (!lex || id != "Include")
842 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
844 InsetInclude inset(params);
846 params = inset.params();
851 InsetIncludeMailer::params2string(InsetCommandParams const & params)
853 InsetInclude inset(params);
855 data << name_ << ' ';
857 data << "\\end_inset\n";