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"
34 #include "frontends/Alert.h"
35 #include "frontends/LyXView.h"
36 #include "frontends/Painter.h"
38 #include "graphics/PreviewImage.h"
39 #include "graphics/PreviewLoader.h"
41 #include "insets/render_preview.h"
43 #include "support/filename.h"
44 #include "support/filetools.h"
45 #include "support/lstrings.h" // contains
46 #include "support/lyxlib.h"
47 #include "support/convert.h"
49 #include <boost/bind.hpp>
50 #include <boost/filesystem/operations.hpp>
52 #include "support/std_ostream.h"
56 using lyx::support::addName;
57 using lyx::support::absolutePath;
58 using lyx::support::bformat;
59 using lyx::support::changeExtension;
60 using lyx::support::contains;
61 using lyx::support::copy;
62 using lyx::support::FileName;
63 using lyx::support::getFileContents;
64 using lyx::support::isFileReadable;
65 using lyx::support::isLyXFilename;
66 using lyx::support::latex_path;
67 using lyx::support::makeAbsPath;
68 using lyx::support::makeDisplayPath;
69 using lyx::support::makeRelPath;
70 using lyx::support::onlyFilename;
71 using lyx::support::onlyPath;
72 using lyx::support::subst;
73 using lyx::support::sum;
78 using std::istringstream;
80 using std::ostringstream;
82 namespace fs = boost::filesystem;
84 extern BufferList bufferlist;
89 string const uniqueID()
91 static unsigned int seed = 1000;
92 return "file" + convert<string>(++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(LCursor & cur, FuncRequest & cmd)
126 switch (cmd.action) {
128 case LFUN_INSET_MODIFY: {
129 InsetCommandParams p;
130 InsetIncludeMailer::string2params(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 case LFUN_INSET_DIALOG_SHOW:
145 InsetIncludeMailer(*this).showDialog(&cur.bv());
149 InsetBase::doDispatch(cur, cmd);
155 bool InsetInclude::getStatus(LCursor & cur, FuncRequest const & cmd,
156 FuncStatus & flag) const
158 switch (cmd.action) {
160 case LFUN_INSET_MODIFY:
161 case LFUN_INSET_DIALOG_UPDATE:
162 case LFUN_INSET_DIALOG_SHOW:
167 return InsetBase::getStatus(cur, cmd, flag);
172 InsetCommandParams const & InsetInclude::params() const
180 /// the type of inclusion
189 Types type(InsetCommandParams const & params)
191 string const command_name = params.getCmdName();
193 if (command_name == "input")
195 if (command_name == "verbatiminput")
197 if (command_name == "verbatiminput*")
203 bool isVerbatim(InsetCommandParams const & params)
205 string const command_name = params.getCmdName();
206 return command_name == "verbatiminput" ||
207 command_name == "verbatiminput*";
211 string const masterFilename(Buffer const & buffer)
213 return buffer.getMasterBuffer()->fileName();
217 string const parentFilename(Buffer const & buffer)
219 return buffer.fileName();
223 string const includedFilename(Buffer const & buffer,
224 InsetCommandParams const & params)
226 return makeAbsPath(params.getContents(),
227 onlyPath(parentFilename(buffer)));
231 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
236 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
241 if (preview_->monitoring())
242 preview_->stopMonitoring();
244 if (type(params_) == INPUT)
245 add_preview(*preview_, *this, buffer);
249 auto_ptr<InsetBase> InsetInclude::doClone() const
251 return auto_ptr<InsetBase>(new InsetInclude(*this));
255 void InsetInclude::write(Buffer const &, ostream & os) const
261 void InsetInclude::write(ostream & os) const
263 os << "Include " << params_.getCommand() << '\n'
264 << "preview " << convert<string>(params_.preview()) << '\n';
268 void InsetInclude::read(Buffer const &, LyXLex & lex)
274 void InsetInclude::read(LyXLex & lex)
280 string const InsetInclude::getScreenLabel(Buffer const &) const
284 switch (type(params_)) {
285 case INPUT: temp += _("Input"); break;
286 case VERB: temp += _("Verbatim Input"); break;
287 case VERBAST: temp += _("Verbatim Input*"); break;
288 case INCLUDE: temp += _("Include"); break;
293 if (params_.getContents().empty())
296 temp += onlyFilename(params_.getContents());
304 /// return true if the file is or got loaded.
305 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
307 if (isVerbatim(params))
310 string const included_file = includedFilename(buffer, params);
311 if (!isLyXFilename(included_file))
314 Buffer * buf = bufferlist.getBuffer(included_file);
316 // the readonly flag can/will be wrong, not anymore I think.
317 if (!fs::exists(included_file))
319 buf = bufferlist.newBuffer(included_file);
320 if (!loadLyXFile(buf, included_file))
324 buf->setParentName(parentFilename(buffer));
332 int InsetInclude::latex(Buffer const & buffer, ostream & os,
333 OutputParams const & runparams) const
335 string incfile(params_.getContents());
337 // Do nothing if no file name has been specified
341 string const included_file = includedFilename(buffer, params_);
342 Buffer const * const m_buffer = buffer.getMasterBuffer();
344 // if incfile is relative, make it relative to the master
346 if (!absolutePath(incfile)) {
347 incfile = makeRelPath(included_file,
348 m_buffer->filePath());
351 // write it to a file (so far the complete file)
352 string const exportfile = changeExtension(incfile, ".tex");
353 string const mangled = FileName(changeExtension(included_file,
354 ".tex")).mangledFilename();
355 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
359 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
360 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
361 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
363 if (runparams.inComment || runparams.dryrun)
364 // Don't try to load or copy the file
366 else if (loadIfNeeded(buffer, params_)) {
367 Buffer * tmp = bufferlist.getBuffer(included_file);
369 if (tmp->params().textclass != m_buffer->params().textclass) {
370 string text = bformat(_("Included file `%1$s'\n"
371 "has textclass `%2$s'\n"
372 "while parent file has textclass `%3$s'."),
373 makeDisplayPath(included_file),
374 tmp->params().getLyXTextClass().name(),
375 m_buffer->params().getLyXTextClass().name());
376 Alert::warning(_("Different textclasses"), text);
380 tmp->markDepClean(m_buffer->temppath());
383 #warning handle non existing files
384 #warning Second argument is irrelevant!
385 // since only_body is true, makeLaTeXFile will not look at second
386 // argument. Should we set it to string(), or should makeLaTeXFile
387 // make use of it somehow? (JMarc 20031002)
389 tmp->makeLaTeXFile(writefile,
390 onlyPath(masterFilename(buffer)),
393 // Copy the file to the temp dir, so that .aux files etc.
394 // are not created in the original dir. Files included by
395 // this file will be found via input@path, see ../buffer.C.
396 unsigned long const checksum_in = sum(included_file);
397 unsigned long const checksum_out = sum(writefile);
399 if (checksum_in != checksum_out) {
400 if (!copy(included_file, writefile)) {
402 << bformat(_("Could not copy the file\n%1$s\n"
403 "into the temporary directory."),
411 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
412 "latex" : "pdflatex";
413 if (isVerbatim(params_)) {
414 incfile = latex_path(incfile);
415 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
416 } else if (type(params_) == INPUT) {
417 runparams.exportdata->addExternalFile(tex_format, writefile,
420 // \input wants file with extension (default is .tex)
421 if (!isLyXFilename(included_file)) {
422 incfile = latex_path(incfile);
423 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
425 incfile = changeExtension(incfile, ".tex");
426 incfile = latex_path(incfile);
427 os << '\\' << params_.getCmdName() << '{'
432 runparams.exportdata->addExternalFile(tex_format, writefile,
435 // \include don't want extension and demands that the
436 // file really have .tex
437 incfile = changeExtension(incfile, string());
438 incfile = latex_path(incfile);
439 os << '\\' << params_.getCmdName() << '{'
448 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
449 OutputParams const &) const
451 if (isVerbatim(params_))
452 os << getFileContents(includedFilename(buffer, params_));
457 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
458 OutputParams const & runparams) const
460 string incfile(params_.getContents());
462 // Do nothing if no file name has been specified
466 string const included_file = includedFilename(buffer, params_);
468 // write it to a file (so far the complete file)
469 string const exportfile = changeExtension(incfile, ".sgml");
470 string writefile = changeExtension(included_file, ".sgml");
472 if (loadIfNeeded(buffer, params_)) {
473 Buffer * tmp = bufferlist.getBuffer(included_file);
475 writefile = makeAbsPath(FileName(writefile).mangledFilename(),
476 buffer.getMasterBuffer()->temppath());
480 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
481 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
482 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
484 tmp->makeLinuxDocFile(writefile, runparams, true);
487 if (isVerbatim(params_)) {
489 << getFileContents(included_file)
492 runparams.exportdata->addExternalFile("linuxdoc", writefile,
494 os << '&' << include_label << ';';
501 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
502 OutputParams const & runparams) const
504 string incfile(params_.getContents());
506 // Do nothing if no file name has been specified
510 string const included_file = includedFilename(buffer, params_);
512 // write it to a file (so far the complete file)
513 string const exportfile = changeExtension(incfile, ".sgml");
514 string writefile = changeExtension(included_file, ".sgml");
516 if (loadIfNeeded(buffer, params_)) {
517 Buffer * tmp = bufferlist.getBuffer(included_file);
519 string const mangled = FileName(writefile).mangledFilename();
520 writefile = makeAbsPath(mangled,
521 buffer.getMasterBuffer()->temppath());
525 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
526 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
527 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
529 tmp->makeDocBookFile(writefile, runparams, true);
532 runparams.exportdata->addExternalFile("docbook", writefile,
534 runparams.exportdata->addExternalFile("docbook-xml", writefile,
537 if (isVerbatim(params_)) {
538 os << "<inlinegraphic fileref=\""
539 << '&' << include_label << ';'
540 << "\" format=\"linespecific\">";
542 os << '&' << include_label << ';';
548 void InsetInclude::validate(LaTeXFeatures & features) const
550 string incfile(params_.getContents());
553 Buffer const & buffer = features.buffer();
555 string const included_file = includedFilename(buffer, params_);
557 if (isLyXFilename(included_file))
558 writefile = changeExtension(included_file, ".sgml");
560 writefile = included_file;
562 if (!features.runparams().nice && !isVerbatim(params_)) {
563 incfile = FileName(writefile).mangledFilename();
564 writefile = makeAbsPath(incfile,
565 buffer.getMasterBuffer()->temppath());
568 features.includeFile(include_label, writefile);
570 if (isVerbatim(params_))
571 features.require("verbatim");
573 // Here we must do the fun stuff...
574 // Load the file in the include if it needs
576 if (loadIfNeeded(buffer, params_)) {
578 Buffer * const tmp = bufferlist.getBuffer(included_file);
580 // We must temporarily change features.buffer,
581 // otherwise it would always be the master buffer,
582 // and nested includes would not work.
583 features.setBuffer(*tmp);
584 tmp->validate(features);
585 features.setBuffer(buffer);
591 void InsetInclude::getLabelList(Buffer const & buffer,
592 std::vector<string> & list) const
594 if (loadIfNeeded(buffer, params_)) {
595 string const included_file = includedFilename(buffer, params_);
596 Buffer * tmp = bufferlist.getBuffer(included_file);
597 tmp->setParentName("");
598 tmp->getLabelList(list);
599 tmp->setParentName(parentFilename(buffer));
604 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
605 std::vector<std::pair<string,string> > & keys) const
607 if (loadIfNeeded(buffer, params_)) {
608 string const included_file = includedFilename(buffer, params_);
609 Buffer * tmp = bufferlist.getBuffer(included_file);
610 tmp->setParentName("");
611 tmp->fillWithBibKeys(keys);
612 tmp->setParentName(parentFilename(buffer));
617 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
619 if (loadIfNeeded(buffer, params_)) {
620 string const included_file = includedFilename(buffer, params_);
621 Buffer * tmp = bufferlist.getBuffer(included_file);
622 tmp->setParentName("");
623 tmp->updateBibfilesCache();
624 tmp->setParentName(parentFilename(buffer));
629 std::vector<string> const &
630 InsetInclude::getBibfilesCache(Buffer const & buffer) const
632 if (loadIfNeeded(buffer, params_)) {
633 string const included_file = includedFilename(buffer, params_);
634 Buffer * tmp = bufferlist.getBuffer(included_file);
635 tmp->setParentName("");
636 std::vector<string> const & cache = tmp->getBibfilesCache();
637 tmp->setParentName(parentFilename(buffer));
640 static std::vector<string> const empty;
645 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
647 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
649 bool use_preview = false;
650 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
651 lyx::graphics::PreviewImage const * pimage =
652 preview_->getPreviewImage(*mi.base.bv->buffer());
653 use_preview = pimage && pimage->image();
657 preview_->metrics(mi, dim);
661 button_.update(getScreenLabel(*mi.base.bv->buffer()),
664 button_.metrics(mi, dim);
667 Box b(0, dim.wid, -dim.asc, dim.des);
674 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
676 setPosCache(pi, x, y);
678 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
680 bool use_preview = false;
681 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
682 lyx::graphics::PreviewImage const * pimage =
683 preview_->getPreviewImage(*pi.base.bv->buffer());
684 use_preview = pimage && pimage->image();
688 preview_->draw(pi, x, y);
690 button_.draw(pi, x, y);
693 bool InsetInclude::display() const
695 return type(params_) != INPUT;
704 void InsetInclude::fileChanged() const
706 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
710 Buffer const & buffer = *buffer_ptr;
711 preview_->removePreview(buffer);
712 add_preview(*preview_.get(), *this, buffer);
713 preview_->startLoading(buffer);
719 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
721 string const included_file = includedFilename(buffer, params);
723 return type(params) == INPUT && params.preview() &&
724 isFileReadable(included_file);
728 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
731 OutputParams runparams;
732 runparams.flavor = OutputParams::LATEX;
733 inset.latex(buffer, os, runparams);
739 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
740 Buffer const & buffer)
742 InsetCommandParams const & params = inset.params();
743 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
744 preview_wanted(params, buffer)) {
745 renderer.setAbsFile(includedFilename(buffer, params));
746 string const snippet = latex_string(inset, buffer);
747 renderer.addPreview(snippet, buffer);
754 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
756 Buffer const & buffer = ploader.buffer();
757 if (preview_wanted(params(), buffer)) {
758 preview_->setAbsFile(includedFilename(buffer, params()));
759 string const snippet = latex_string(*this, buffer);
760 preview_->addPreview(snippet, ploader);
765 string const InsetIncludeMailer::name_("include");
767 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
772 string const InsetIncludeMailer::inset2string(Buffer const &) const
774 return params2string(inset_.params());
778 void InsetIncludeMailer::string2params(string const & in,
779 InsetCommandParams & params)
781 params = InsetCommandParams();
785 istringstream data(in);
791 if (!lex || name != name_)
792 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
794 // This is part of the inset proper that is usually swallowed
795 // by LyXText::readInset
798 if (!lex || id != "Include")
799 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
801 InsetInclude inset(params);
803 params = inset.params();
808 InsetIncludeMailer::params2string(InsetCommandParams const & params)
810 InsetInclude inset(params);
812 data << name_ << ' ';
814 data << "\\end_inset\n";