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 the child buffer if the file is a LyX doc and is loaded
305 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
307 if (isVerbatim(params))
310 string const included_file = includedFilename(buffer, params);
311 if (!isLyXFilename(included_file))
314 return bufferlist.getBuffer(included_file);
318 /// return true if the file is or got loaded.
319 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
321 if (isVerbatim(params))
324 string const included_file = includedFilename(buffer, params);
325 if (!isLyXFilename(included_file))
328 Buffer * buf = bufferlist.getBuffer(included_file);
330 // the readonly flag can/will be wrong, not anymore I think.
331 if (!fs::exists(included_file))
333 buf = bufferlist.newBuffer(included_file);
334 if (!loadLyXFile(buf, included_file))
338 buf->setParentName(parentFilename(buffer));
346 int InsetInclude::latex(Buffer const & buffer, ostream & os,
347 OutputParams const & runparams) const
349 string incfile(params_.getContents());
351 // Do nothing if no file name has been specified
355 string const included_file = includedFilename(buffer, params_);
356 Buffer const * const m_buffer = buffer.getMasterBuffer();
358 // if incfile is relative, make it relative to the master
360 if (!absolutePath(incfile)) {
361 incfile = makeRelPath(included_file,
362 m_buffer->filePath());
365 // write it to a file (so far the complete file)
366 string const exportfile = changeExtension(incfile, ".tex");
367 string const mangled = FileName(changeExtension(included_file,
368 ".tex")).mangledFilename();
369 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
373 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
374 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
375 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
377 if (runparams.inComment || runparams.dryrun)
378 // Don't try to load or copy the file
380 else if (loadIfNeeded(buffer, params_)) {
381 Buffer * tmp = bufferlist.getBuffer(included_file);
383 if (tmp->params().textclass != m_buffer->params().textclass) {
384 string text = bformat(_("Included file `%1$s'\n"
385 "has textclass `%2$s'\n"
386 "while parent file has textclass `%3$s'."),
387 makeDisplayPath(included_file),
388 tmp->params().getLyXTextClass().name(),
389 m_buffer->params().getLyXTextClass().name());
390 Alert::warning(_("Different textclasses"), text);
394 tmp->markDepClean(m_buffer->temppath());
397 #warning handle non existing files
398 #warning Second argument is irrelevant!
399 // since only_body is true, makeLaTeXFile will not look at second
400 // argument. Should we set it to string(), or should makeLaTeXFile
401 // make use of it somehow? (JMarc 20031002)
403 tmp->makeLaTeXFile(writefile,
404 onlyPath(masterFilename(buffer)),
407 // Copy the file to the temp dir, so that .aux files etc.
408 // are not created in the original dir. Files included by
409 // this file will be found via input@path, see ../buffer.C.
410 unsigned long const checksum_in = sum(included_file);
411 unsigned long const checksum_out = sum(writefile);
413 if (checksum_in != checksum_out) {
414 if (!copy(included_file, writefile)) {
416 << bformat(_("Could not copy the file\n%1$s\n"
417 "into the temporary directory."),
425 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
426 "latex" : "pdflatex";
427 if (isVerbatim(params_)) {
428 incfile = latex_path(incfile);
429 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
430 } else if (type(params_) == INPUT) {
431 runparams.exportdata->addExternalFile(tex_format, writefile,
434 // \input wants file with extension (default is .tex)
435 if (!isLyXFilename(included_file)) {
436 incfile = latex_path(incfile);
437 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
439 incfile = changeExtension(incfile, ".tex");
440 incfile = latex_path(incfile);
441 os << '\\' << params_.getCmdName() << '{'
446 runparams.exportdata->addExternalFile(tex_format, writefile,
449 // \include don't want extension and demands that the
450 // file really have .tex
451 incfile = changeExtension(incfile, string());
452 incfile = latex_path(incfile);
453 os << '\\' << params_.getCmdName() << '{'
462 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
463 OutputParams const &) const
465 if (isVerbatim(params_))
466 os << getFileContents(includedFilename(buffer, params_));
471 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
472 OutputParams const & runparams) const
474 string incfile(params_.getContents());
476 // Do nothing if no file name has been specified
480 string const included_file = includedFilename(buffer, params_);
482 // write it to a file (so far the complete file)
483 string const exportfile = changeExtension(incfile, ".sgml");
484 string writefile = changeExtension(included_file, ".sgml");
486 if (loadIfNeeded(buffer, params_)) {
487 Buffer * tmp = bufferlist.getBuffer(included_file);
489 writefile = makeAbsPath(FileName(writefile).mangledFilename(),
490 buffer.getMasterBuffer()->temppath());
494 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
495 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
496 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
498 tmp->makeLinuxDocFile(writefile, runparams, true);
501 if (isVerbatim(params_)) {
503 << getFileContents(included_file)
506 runparams.exportdata->addExternalFile("linuxdoc", writefile,
508 os << '&' << include_label << ';';
515 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
516 OutputParams const & runparams) const
518 string incfile(params_.getContents());
520 // Do nothing if no file name has been specified
524 string const included_file = includedFilename(buffer, params_);
526 // write it to a file (so far the complete file)
527 string const exportfile = changeExtension(incfile, ".sgml");
528 string writefile = changeExtension(included_file, ".sgml");
530 if (loadIfNeeded(buffer, params_)) {
531 Buffer * tmp = bufferlist.getBuffer(included_file);
533 string const mangled = FileName(writefile).mangledFilename();
534 writefile = makeAbsPath(mangled,
535 buffer.getMasterBuffer()->temppath());
539 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
540 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
541 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
543 tmp->makeDocBookFile(writefile, runparams, true);
546 runparams.exportdata->addExternalFile("docbook", writefile,
548 runparams.exportdata->addExternalFile("docbook-xml", writefile,
551 if (isVerbatim(params_)) {
552 os << "<inlinegraphic fileref=\""
553 << '&' << include_label << ';'
554 << "\" format=\"linespecific\">";
556 os << '&' << include_label << ';';
562 void InsetInclude::validate(LaTeXFeatures & features) const
564 string incfile(params_.getContents());
567 Buffer const & buffer = features.buffer();
569 string const included_file = includedFilename(buffer, params_);
571 if (isLyXFilename(included_file))
572 writefile = changeExtension(included_file, ".sgml");
574 writefile = included_file;
576 if (!features.runparams().nice && !isVerbatim(params_)) {
577 incfile = FileName(writefile).mangledFilename();
578 writefile = makeAbsPath(incfile,
579 buffer.getMasterBuffer()->temppath());
582 features.includeFile(include_label, writefile);
584 if (isVerbatim(params_))
585 features.require("verbatim");
587 // Here we must do the fun stuff...
588 // Load the file in the include if it needs
590 if (loadIfNeeded(buffer, params_)) {
592 Buffer * const tmp = bufferlist.getBuffer(included_file);
594 // We must temporarily change features.buffer,
595 // otherwise it would always be the master buffer,
596 // and nested includes would not work.
597 features.setBuffer(*tmp);
598 tmp->validate(features);
599 features.setBuffer(buffer);
605 void InsetInclude::getLabelList(Buffer const & buffer,
606 std::vector<string> & list) const
608 if (loadIfNeeded(buffer, params_)) {
609 string const included_file = includedFilename(buffer, params_);
610 Buffer * tmp = bufferlist.getBuffer(included_file);
611 tmp->setParentName("");
612 tmp->getLabelList(list);
613 tmp->setParentName(parentFilename(buffer));
618 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
619 std::vector<std::pair<string,string> > & keys) const
621 if (loadIfNeeded(buffer, params_)) {
622 string const included_file = includedFilename(buffer, params_);
623 Buffer * tmp = bufferlist.getBuffer(included_file);
624 tmp->setParentName("");
625 tmp->fillWithBibKeys(keys);
626 tmp->setParentName(parentFilename(buffer));
631 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
633 Buffer * const tmp = getChildBuffer(buffer, params_);
635 tmp->setParentName("");
636 tmp->updateBibfilesCache();
637 tmp->setParentName(parentFilename(buffer));
642 std::vector<string> const &
643 InsetInclude::getBibfilesCache(Buffer const & buffer) const
645 Buffer * const tmp = getChildBuffer(buffer, params_);
647 tmp->setParentName("");
648 std::vector<string> const & cache = tmp->getBibfilesCache();
649 tmp->setParentName(parentFilename(buffer));
652 static std::vector<string> const empty;
657 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
659 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
661 bool use_preview = false;
662 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
663 lyx::graphics::PreviewImage const * pimage =
664 preview_->getPreviewImage(*mi.base.bv->buffer());
665 use_preview = pimage && pimage->image();
669 preview_->metrics(mi, dim);
673 button_.update(getScreenLabel(*mi.base.bv->buffer()),
676 button_.metrics(mi, dim);
679 Box b(0, dim.wid, -dim.asc, dim.des);
686 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
688 setPosCache(pi, x, y);
690 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
692 bool use_preview = false;
693 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
694 lyx::graphics::PreviewImage const * pimage =
695 preview_->getPreviewImage(*pi.base.bv->buffer());
696 use_preview = pimage && pimage->image();
700 preview_->draw(pi, x, y);
702 button_.draw(pi, x, y);
705 bool InsetInclude::display() const
707 return type(params_) != INPUT;
716 void InsetInclude::fileChanged() const
718 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
722 Buffer const & buffer = *buffer_ptr;
723 preview_->removePreview(buffer);
724 add_preview(*preview_.get(), *this, buffer);
725 preview_->startLoading(buffer);
731 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
733 string const included_file = includedFilename(buffer, params);
735 return type(params) == INPUT && params.preview() &&
736 isFileReadable(included_file);
740 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
743 OutputParams runparams;
744 runparams.flavor = OutputParams::LATEX;
745 inset.latex(buffer, os, runparams);
751 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
752 Buffer const & buffer)
754 InsetCommandParams const & params = inset.params();
755 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
756 preview_wanted(params, buffer)) {
757 renderer.setAbsFile(includedFilename(buffer, params));
758 string const snippet = latex_string(inset, buffer);
759 renderer.addPreview(snippet, buffer);
766 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
768 Buffer const & buffer = ploader.buffer();
769 if (preview_wanted(params(), buffer)) {
770 preview_->setAbsFile(includedFilename(buffer, params()));
771 string const snippet = latex_string(*this, buffer);
772 preview_->addPreview(snippet, ploader);
777 string const InsetIncludeMailer::name_("include");
779 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
784 string const InsetIncludeMailer::inset2string(Buffer const &) const
786 return params2string(inset_.params());
790 void InsetIncludeMailer::string2params(string const & in,
791 InsetCommandParams & params)
793 params = InsetCommandParams();
797 istringstream data(in);
803 if (!lex || name != name_)
804 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
806 // This is part of the inset proper that is usually swallowed
807 // by LyXText::readInset
810 if (!lex || id != "Include")
811 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
813 InsetInclude inset(params);
815 params = inset.params();
820 InsetIncludeMailer::params2string(InsetCommandParams const & params)
822 InsetInclude inset(params);
824 data << name_ << ' ';
826 data << "\\end_inset\n";