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 InsetIncludeMailer(*this).showDialog(&cur.bv());
148 InsetBase::doDispatch(cur, cmd);
154 bool InsetInclude::getStatus(LCursor & 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 InsetBase::getStatus(cur, cmd, flag);
170 InsetCommandParams const & InsetInclude::params() const
178 /// the type of inclusion
187 Types type(InsetCommandParams const & params)
189 string const command_name = params.getCmdName();
191 if (command_name == "input")
193 if (command_name == "verbatiminput")
195 if (command_name == "verbatiminput*")
201 bool isVerbatim(InsetCommandParams const & params)
203 string const command_name = params.getCmdName();
204 return command_name == "verbatiminput" ||
205 command_name == "verbatiminput*";
209 string const masterFilename(Buffer const & buffer)
211 return buffer.getMasterBuffer()->fileName();
215 string const parentFilename(Buffer const & buffer)
217 return buffer.fileName();
221 string const includedFilename(Buffer const & buffer,
222 InsetCommandParams const & params)
224 return makeAbsPath(params.getContents(),
225 onlyPath(parentFilename(buffer)));
229 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
234 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
239 if (preview_->monitoring())
240 preview_->stopMonitoring();
242 if (type(params_) == INPUT)
243 add_preview(*preview_, *this, buffer);
247 auto_ptr<InsetBase> InsetInclude::doClone() const
249 return auto_ptr<InsetBase>(new InsetInclude(*this));
253 void InsetInclude::write(Buffer const &, ostream & os) const
259 void InsetInclude::write(ostream & os) const
261 os << "Include " << params_.getCommand() << '\n'
262 << "preview " << convert<string>(params_.preview()) << '\n';
266 void InsetInclude::read(Buffer const &, LyXLex & lex)
272 void InsetInclude::read(LyXLex & lex)
278 string const InsetInclude::getScreenLabel(Buffer const &) const
282 switch (type(params_)) {
283 case INPUT: temp += _("Input"); break;
284 case VERB: temp += _("Verbatim Input"); break;
285 case VERBAST: temp += _("Verbatim Input*"); break;
286 case INCLUDE: temp += _("Include"); break;
291 if (params_.getContents().empty())
294 temp += onlyFilename(params_.getContents());
302 /// return the child buffer if the file is a LyX doc and is loaded
303 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
305 if (isVerbatim(params))
308 string const included_file = includedFilename(buffer, params);
309 if (!isLyXFilename(included_file))
312 return bufferlist.getBuffer(included_file);
316 /// return true if the file is or got loaded.
317 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
319 if (isVerbatim(params))
322 string const included_file = includedFilename(buffer, params);
323 if (!isLyXFilename(included_file))
326 Buffer * buf = bufferlist.getBuffer(included_file);
328 // the readonly flag can/will be wrong, not anymore I think.
329 if (!fs::exists(included_file))
331 buf = bufferlist.newBuffer(included_file);
332 if (!loadLyXFile(buf, included_file))
336 buf->setParentName(parentFilename(buffer));
344 int InsetInclude::latex(Buffer const & buffer, ostream & os,
345 OutputParams const & runparams) const
347 string incfile(params_.getContents());
349 // Do nothing if no file name has been specified
353 string const included_file = includedFilename(buffer, params_);
354 Buffer const * const m_buffer = buffer.getMasterBuffer();
356 // if incfile is relative, make it relative to the master
358 if (!absolutePath(incfile)) {
359 incfile = makeRelPath(included_file,
360 m_buffer->filePath());
363 // write it to a file (so far the complete file)
364 string const exportfile = changeExtension(incfile, ".tex");
365 string const mangled = FileName(changeExtension(included_file,
366 ".tex")).mangledFilename();
367 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
371 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
372 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
373 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
375 if (runparams.inComment || runparams.dryrun)
376 // Don't try to load or copy the file
378 else if (loadIfNeeded(buffer, params_)) {
379 Buffer * tmp = bufferlist.getBuffer(included_file);
381 if (tmp->params().textclass != m_buffer->params().textclass) {
382 string text = bformat(_("Included file `%1$s'\n"
383 "has textclass `%2$s'\n"
384 "while parent file has textclass `%3$s'."),
385 makeDisplayPath(included_file),
386 tmp->params().getLyXTextClass().name(),
387 m_buffer->params().getLyXTextClass().name());
388 Alert::warning(_("Different textclasses"), text);
392 tmp->markDepClean(m_buffer->temppath());
395 #warning handle non existing files
396 #warning Second argument is irrelevant!
397 // since only_body is true, makeLaTeXFile will not look at second
398 // argument. Should we set it to string(), or should makeLaTeXFile
399 // make use of it somehow? (JMarc 20031002)
401 tmp->makeLaTeXFile(writefile,
402 onlyPath(masterFilename(buffer)),
405 // Copy the file to the temp dir, so that .aux files etc.
406 // are not created in the original dir. Files included by
407 // this file will be found via input@path, see ../buffer.C.
408 unsigned long const checksum_in = sum(included_file);
409 unsigned long const checksum_out = sum(writefile);
411 if (checksum_in != checksum_out) {
412 if (!copy(included_file, writefile)) {
414 << bformat(_("Could not copy the file\n%1$s\n"
415 "into the temporary directory."),
423 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
424 "latex" : "pdflatex";
425 if (isVerbatim(params_)) {
426 incfile = latex_path(incfile);
427 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
428 } else if (type(params_) == INPUT) {
429 runparams.exportdata->addExternalFile(tex_format, writefile,
432 // \input wants file with extension (default is .tex)
433 if (!isLyXFilename(included_file)) {
434 incfile = latex_path(incfile);
435 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
437 incfile = changeExtension(incfile, ".tex");
438 incfile = latex_path(incfile);
439 os << '\\' << params_.getCmdName() << '{'
444 runparams.exportdata->addExternalFile(tex_format, writefile,
447 // \include don't want extension and demands that the
448 // file really have .tex
449 incfile = changeExtension(incfile, string());
450 incfile = latex_path(incfile);
451 os << '\\' << params_.getCmdName() << '{'
460 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
461 OutputParams const &) const
463 if (isVerbatim(params_))
464 os << getFileContents(includedFilename(buffer, params_));
469 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
470 OutputParams const & runparams) const
472 string incfile(params_.getContents());
474 // Do nothing if no file name has been specified
478 string const included_file = includedFilename(buffer, params_);
480 // write it to a file (so far the complete file)
481 string const exportfile = changeExtension(incfile, ".sgml");
482 string writefile = changeExtension(included_file, ".sgml");
484 if (loadIfNeeded(buffer, params_)) {
485 Buffer * tmp = bufferlist.getBuffer(included_file);
487 writefile = makeAbsPath(FileName(writefile).mangledFilename(),
488 buffer.getMasterBuffer()->temppath());
492 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
493 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
494 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
496 tmp->makeLinuxDocFile(writefile, runparams, true);
499 if (isVerbatim(params_)) {
501 << getFileContents(included_file)
504 runparams.exportdata->addExternalFile("linuxdoc", writefile,
506 os << '&' << include_label << ';';
513 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
514 OutputParams const & runparams) const
516 string incfile(params_.getContents());
518 // Do nothing if no file name has been specified
522 string const included_file = includedFilename(buffer, params_);
524 // write it to a file (so far the complete file)
525 string const exportfile = changeExtension(incfile, ".sgml");
526 string writefile = changeExtension(included_file, ".sgml");
528 if (loadIfNeeded(buffer, params_)) {
529 Buffer * tmp = bufferlist.getBuffer(included_file);
531 string const mangled = FileName(writefile).mangledFilename();
532 writefile = makeAbsPath(mangled,
533 buffer.getMasterBuffer()->temppath());
537 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
538 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
539 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
541 tmp->makeDocBookFile(writefile, runparams, true);
544 runparams.exportdata->addExternalFile("docbook", writefile,
546 runparams.exportdata->addExternalFile("docbook-xml", writefile,
549 if (isVerbatim(params_)) {
550 os << "<inlinegraphic fileref=\""
551 << '&' << include_label << ';'
552 << "\" format=\"linespecific\">";
554 os << '&' << include_label << ';';
560 void InsetInclude::validate(LaTeXFeatures & features) const
562 string incfile(params_.getContents());
565 Buffer const & buffer = features.buffer();
567 string const included_file = includedFilename(buffer, params_);
569 if (isLyXFilename(included_file))
570 writefile = changeExtension(included_file, ".sgml");
572 writefile = included_file;
574 if (!features.runparams().nice && !isVerbatim(params_)) {
575 incfile = FileName(writefile).mangledFilename();
576 writefile = makeAbsPath(incfile,
577 buffer.getMasterBuffer()->temppath());
580 features.includeFile(include_label, writefile);
582 if (isVerbatim(params_))
583 features.require("verbatim");
585 // Here we must do the fun stuff...
586 // Load the file in the include if it needs
588 if (loadIfNeeded(buffer, params_)) {
590 Buffer * const tmp = bufferlist.getBuffer(included_file);
592 // We must temporarily change features.buffer,
593 // otherwise it would always be the master buffer,
594 // and nested includes would not work.
595 features.setBuffer(*tmp);
596 tmp->validate(features);
597 features.setBuffer(buffer);
603 void InsetInclude::getLabelList(Buffer const & buffer,
604 std::vector<string> & list) const
606 if (loadIfNeeded(buffer, params_)) {
607 string const included_file = includedFilename(buffer, params_);
608 Buffer * tmp = bufferlist.getBuffer(included_file);
609 tmp->setParentName("");
610 tmp->getLabelList(list);
611 tmp->setParentName(parentFilename(buffer));
616 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
617 std::vector<std::pair<string,string> > & keys) const
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->fillWithBibKeys(keys);
624 tmp->setParentName(parentFilename(buffer));
629 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
631 Buffer * const tmp = getChildBuffer(buffer, params_);
633 tmp->setParentName("");
634 tmp->updateBibfilesCache();
635 tmp->setParentName(parentFilename(buffer));
640 std::vector<string> const &
641 InsetInclude::getBibfilesCache(Buffer const & buffer) const
643 Buffer * const tmp = getChildBuffer(buffer, params_);
645 tmp->setParentName("");
646 std::vector<string> const & cache = tmp->getBibfilesCache();
647 tmp->setParentName(parentFilename(buffer));
650 static std::vector<string> const empty;
655 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
657 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
659 bool use_preview = false;
660 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
661 lyx::graphics::PreviewImage const * pimage =
662 preview_->getPreviewImage(*mi.base.bv->buffer());
663 use_preview = pimage && pimage->image();
667 preview_->metrics(mi, dim);
671 button_.update(getScreenLabel(*mi.base.bv->buffer()),
674 button_.metrics(mi, dim);
677 Box b(0, dim.wid, -dim.asc, dim.des);
684 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
686 setPosCache(pi, x, y);
688 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
690 bool use_preview = false;
691 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
692 lyx::graphics::PreviewImage const * pimage =
693 preview_->getPreviewImage(*pi.base.bv->buffer());
694 use_preview = pimage && pimage->image();
698 preview_->draw(pi, x, y);
700 button_.draw(pi, x, y);
703 bool InsetInclude::display() const
705 return type(params_) != INPUT;
714 void InsetInclude::fileChanged() const
716 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
720 Buffer const & buffer = *buffer_ptr;
721 preview_->removePreview(buffer);
722 add_preview(*preview_.get(), *this, buffer);
723 preview_->startLoading(buffer);
729 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
731 string const included_file = includedFilename(buffer, params);
733 return type(params) == INPUT && params.preview() &&
734 isFileReadable(included_file);
738 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
741 OutputParams runparams;
742 runparams.flavor = OutputParams::LATEX;
743 inset.latex(buffer, os, runparams);
749 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
750 Buffer const & buffer)
752 InsetCommandParams const & params = inset.params();
753 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
754 preview_wanted(params, buffer)) {
755 renderer.setAbsFile(includedFilename(buffer, params));
756 string const snippet = latex_string(inset, buffer);
757 renderer.addPreview(snippet, buffer);
764 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
766 Buffer const & buffer = ploader.buffer();
767 if (preview_wanted(params(), buffer)) {
768 preview_->setAbsFile(includedFilename(buffer, params()));
769 string const snippet = latex_string(*this, buffer);
770 preview_->addPreview(snippet, ploader);
775 string const InsetIncludeMailer::name_("include");
777 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
782 string const InsetIncludeMailer::inset2string(Buffer const &) const
784 return params2string(inset_.params());
788 void InsetIncludeMailer::string2params(string const & in,
789 InsetCommandParams & params)
791 params = InsetCommandParams();
795 istringstream data(in);
801 if (!lex || name != name_)
802 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
804 // This is part of the inset proper that is usually swallowed
805 // by LyXText::readInset
808 if (!lex || id != "Include")
809 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
811 InsetInclude inset(params);
813 params = inset.params();
818 InsetIncludeMailer::params2string(InsetCommandParams const & params)
820 InsetInclude inset(params);
822 data << name_ << ' ';
824 data << "\\end_inset\n";