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/lyxalgo.h"
44 #include "support/filename.h"
45 #include "support/filetools.h"
46 #include "support/lstrings.h" // contains
47 #include "support/lyxlib.h"
48 #include "support/convert.h"
50 #include <boost/bind.hpp>
51 #include <boost/filesystem/operations.hpp>
53 #include "support/std_ostream.h"
58 using lyx::support::addName;
59 using lyx::support::absolutePath;
60 using lyx::support::bformat;
61 using lyx::support::changeExtension;
62 using lyx::support::contains;
63 using lyx::support::copy;
64 using lyx::support::FileName;
65 using lyx::support::getFileContents;
66 using lyx::support::isFileReadable;
67 using lyx::support::isLyXFilename;
68 using lyx::support::latex_path;
69 using lyx::support::makeAbsPath;
70 using lyx::support::makeDisplayPath;
71 using lyx::support::makeRelPath;
72 using lyx::support::onlyFilename;
73 using lyx::support::onlyPath;
74 using lyx::support::subst;
75 using lyx::support::sum;
80 using std::istringstream;
82 using std::ostringstream;
84 namespace fs = boost::filesystem;
86 extern BufferList bufferlist;
91 string const uniqueID()
93 static unsigned int seed = 1000;
94 return "file" + convert<string>(++seed);
100 InsetInclude::InsetInclude(InsetCommandParams const & p)
101 : params_(p), include_label(uniqueID()),
102 preview_(new RenderMonitoredPreview(this)),
105 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
109 InsetInclude::InsetInclude(InsetInclude const & other)
111 params_(other.params_),
112 include_label(other.include_label),
113 preview_(new RenderMonitoredPreview(this)),
116 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
120 InsetInclude::~InsetInclude()
122 InsetIncludeMailer(*this).hideDialog();
126 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
128 switch (cmd.action) {
130 case LFUN_INSET_MODIFY: {
131 InsetCommandParams p;
132 InsetIncludeMailer::string2params(lyx::to_utf8(cmd.argument()), p);
133 if (!p.getCmdName().empty()) {
134 set(p, cur.buffer());
135 cur.buffer().updateBibfilesCache();
141 case LFUN_INSET_DIALOG_UPDATE:
142 InsetIncludeMailer(*this).updateDialog(&cur.bv());
145 case LFUN_MOUSE_RELEASE:
146 InsetIncludeMailer(*this).showDialog(&cur.bv());
150 InsetBase::doDispatch(cur, cmd);
156 bool InsetInclude::getStatus(LCursor & cur, FuncRequest const & cmd,
157 FuncStatus & flag) const
159 switch (cmd.action) {
161 case LFUN_INSET_MODIFY:
162 case LFUN_INSET_DIALOG_UPDATE:
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_)) {
289 temp += _("Verbatim Input");
292 temp += _("Verbatim Input*");
295 temp += _("Include");
299 temp += lyx::from_ascii(": ");
301 if (params_.getContents().empty())
302 temp += lyx::from_ascii("???");
304 temp += lyx::from_ascii(onlyFilename(params_.getContents()));
307 return lyx::to_utf8(temp);
313 /// return the child buffer if the file is a LyX doc and is loaded
314 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
316 if (isVerbatim(params))
319 string const included_file = includedFilename(buffer, params);
320 if (!isLyXFilename(included_file))
323 return bufferlist.getBuffer(included_file);
327 /// return true if the file is or got loaded.
328 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
330 if (isVerbatim(params))
333 string const included_file = includedFilename(buffer, params);
334 if (!isLyXFilename(included_file))
337 Buffer * buf = bufferlist.getBuffer(included_file);
339 // the readonly flag can/will be wrong, not anymore I think.
340 if (!fs::exists(included_file))
342 buf = bufferlist.newBuffer(included_file);
343 if (!loadLyXFile(buf, included_file))
347 buf->setParentName(parentFilename(buffer));
355 int InsetInclude::latex(Buffer const & buffer, ostream & os,
356 OutputParams const & runparams) const
358 string incfile(params_.getContents());
360 // Do nothing if no file name has been specified
364 string const included_file = includedFilename(buffer, params_);
365 Buffer const * const m_buffer = buffer.getMasterBuffer();
367 // if incfile is relative, make it relative to the master
369 if (!absolutePath(incfile)) {
370 incfile = makeRelPath(included_file,
371 m_buffer->filePath());
374 // write it to a file (so far the complete file)
375 string const exportfile = changeExtension(incfile, ".tex");
376 string const mangled = FileName(changeExtension(included_file,
377 ".tex")).mangledFilename();
378 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
382 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
383 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
384 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
386 if (runparams.inComment || runparams.dryrun)
387 // Don't try to load or copy the file
389 else if (loadIfNeeded(buffer, params_)) {
390 Buffer * tmp = bufferlist.getBuffer(included_file);
392 if (tmp->params().textclass != m_buffer->params().textclass) {
394 string text = bformat(lyx::to_utf8(_("Included file `%1$s'\n"
395 "has textclass `%2$s'\n"
396 "while parent file has textclass `%3$s'.")),
397 makeDisplayPath(included_file),
398 tmp->params().getLyXTextClass().name(),
399 m_buffer->params().getLyXTextClass().name());
400 Alert::warning(lyx::to_utf8(_("Different textclasses")), text);
404 tmp->markDepClean(m_buffer->temppath());
407 #warning handle non existing files
408 #warning Second argument is irrelevant!
409 // since only_body is true, makeLaTeXFile will not look at second
410 // argument. Should we set it to string(), or should makeLaTeXFile
411 // make use of it somehow? (JMarc 20031002)
413 tmp->makeLaTeXFile(writefile,
414 onlyPath(masterFilename(buffer)),
417 // Copy the file to the temp dir, so that .aux files etc.
418 // are not created in the original dir. Files included by
419 // this file will be found via input@path, see ../buffer.C.
420 unsigned long const checksum_in = sum(included_file);
421 unsigned long const checksum_out = sum(writefile);
423 if (checksum_in != checksum_out) {
424 if (!copy(included_file, writefile)) {
427 << bformat(lyx::to_utf8(_("Could not copy the file\n%1$s\n"
428 "into the temporary directory.")),
436 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
437 "latex" : "pdflatex";
438 if (isVerbatim(params_)) {
439 incfile = latex_path(incfile);
440 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
441 } else if (type(params_) == INPUT) {
442 runparams.exportdata->addExternalFile(tex_format, writefile,
445 // \input wants file with extension (default is .tex)
446 if (!isLyXFilename(included_file)) {
447 incfile = latex_path(incfile);
448 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
450 incfile = changeExtension(incfile, ".tex");
451 incfile = latex_path(incfile);
452 os << '\\' << params_.getCmdName() << '{'
457 runparams.exportdata->addExternalFile(tex_format, writefile,
460 // \include don't want extension and demands that the
461 // file really have .tex
462 incfile = changeExtension(incfile, string());
463 incfile = latex_path(incfile);
464 os << '\\' << params_.getCmdName() << '{'
473 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
474 OutputParams const &) const
476 if (isVerbatim(params_)) {
478 getFileContents(includedFilename(buffer, params_));
480 // Return how many newlines we issued.
481 return int(lyx::count(str.begin(), str.end(), '\n'));
487 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
488 OutputParams const & runparams) const
490 string incfile(params_.getContents());
492 // Do nothing if no file name has been specified
496 string const included_file = includedFilename(buffer, params_);
498 // write it to a file (so far the complete file)
499 string const exportfile = changeExtension(incfile, ".sgml");
500 string writefile = changeExtension(included_file, ".sgml");
502 if (loadIfNeeded(buffer, params_)) {
503 Buffer * tmp = bufferlist.getBuffer(included_file);
505 string const mangled = FileName(writefile).mangledFilename();
506 writefile = makeAbsPath(mangled,
507 buffer.getMasterBuffer()->temppath());
511 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
512 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
513 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
515 tmp->makeDocBookFile(writefile, runparams, true);
518 runparams.exportdata->addExternalFile("docbook", writefile,
520 runparams.exportdata->addExternalFile("docbook-xml", writefile,
523 if (isVerbatim(params_)) {
524 os << "<inlinegraphic fileref=\""
525 << '&' << include_label << ';'
526 << "\" format=\"linespecific\">";
528 os << '&' << include_label << ';';
534 void InsetInclude::validate(LaTeXFeatures & features) const
536 string incfile(params_.getContents());
539 Buffer const & buffer = features.buffer();
541 string const included_file = includedFilename(buffer, params_);
543 if (isLyXFilename(included_file))
544 writefile = changeExtension(included_file, ".sgml");
546 writefile = included_file;
548 if (!features.runparams().nice && !isVerbatim(params_)) {
549 incfile = FileName(writefile).mangledFilename();
550 writefile = makeAbsPath(incfile,
551 buffer.getMasterBuffer()->temppath());
554 features.includeFile(include_label, writefile);
556 if (isVerbatim(params_))
557 features.require("verbatim");
559 // Here we must do the fun stuff...
560 // Load the file in the include if it needs
562 if (loadIfNeeded(buffer, params_)) {
564 Buffer * const tmp = bufferlist.getBuffer(included_file);
566 // We must temporarily change features.buffer,
567 // otherwise it would always be the master buffer,
568 // and nested includes would not work.
569 features.setBuffer(*tmp);
570 tmp->validate(features);
571 features.setBuffer(buffer);
577 void InsetInclude::getLabelList(Buffer const & buffer,
578 std::vector<string> & list) const
580 if (loadIfNeeded(buffer, params_)) {
581 string const included_file = includedFilename(buffer, params_);
582 Buffer * tmp = bufferlist.getBuffer(included_file);
583 tmp->setParentName("");
584 tmp->getLabelList(list);
585 tmp->setParentName(parentFilename(buffer));
590 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
591 std::vector<std::pair<string,string> > & keys) const
593 if (loadIfNeeded(buffer, params_)) {
594 string const included_file = includedFilename(buffer, params_);
595 Buffer * tmp = bufferlist.getBuffer(included_file);
596 tmp->setParentName("");
597 tmp->fillWithBibKeys(keys);
598 tmp->setParentName(parentFilename(buffer));
603 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
605 Buffer * const tmp = getChildBuffer(buffer, params_);
607 tmp->setParentName("");
608 tmp->updateBibfilesCache();
609 tmp->setParentName(parentFilename(buffer));
614 std::vector<string> const &
615 InsetInclude::getBibfilesCache(Buffer const & buffer) const
617 Buffer * const tmp = getChildBuffer(buffer, params_);
619 tmp->setParentName("");
620 std::vector<string> const & cache = tmp->getBibfilesCache();
621 tmp->setParentName(parentFilename(buffer));
624 static std::vector<string> const empty;
629 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
631 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
633 bool use_preview = false;
634 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
635 lyx::graphics::PreviewImage const * pimage =
636 preview_->getPreviewImage(*mi.base.bv->buffer());
637 use_preview = pimage && pimage->image();
641 preview_->metrics(mi, dim);
645 button_.update(getScreenLabel(*mi.base.bv->buffer()),
648 button_.metrics(mi, dim);
651 Box b(0, dim.wid, -dim.asc, dim.des);
658 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
660 setPosCache(pi, x, y);
662 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
664 bool use_preview = false;
665 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
666 lyx::graphics::PreviewImage const * pimage =
667 preview_->getPreviewImage(*pi.base.bv->buffer());
668 use_preview = pimage && pimage->image();
672 preview_->draw(pi, x, y);
674 button_.draw(pi, x, y);
677 bool InsetInclude::display() const
679 return type(params_) != INPUT;
688 void InsetInclude::fileChanged() const
690 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
694 Buffer const & buffer = *buffer_ptr;
695 preview_->removePreview(buffer);
696 add_preview(*preview_.get(), *this, buffer);
697 preview_->startLoading(buffer);
703 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
705 string const included_file = includedFilename(buffer, params);
707 return type(params) == INPUT && params.preview() &&
708 isFileReadable(included_file);
712 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
715 OutputParams runparams;
716 runparams.flavor = OutputParams::LATEX;
717 inset.latex(buffer, os, runparams);
723 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
724 Buffer const & buffer)
726 InsetCommandParams const & params = inset.params();
727 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
728 preview_wanted(params, buffer)) {
729 renderer.setAbsFile(includedFilename(buffer, params));
730 string const snippet = latex_string(inset, buffer);
731 renderer.addPreview(snippet, buffer);
738 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
740 Buffer const & buffer = ploader.buffer();
741 if (preview_wanted(params(), buffer)) {
742 preview_->setAbsFile(includedFilename(buffer, params()));
743 string const snippet = latex_string(*this, buffer);
744 preview_->addPreview(snippet, ploader);
749 string const InsetIncludeMailer::name_("include");
751 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
756 string const InsetIncludeMailer::inset2string(Buffer const &) const
758 return params2string(inset_.params());
762 void InsetIncludeMailer::string2params(string const & in,
763 InsetCommandParams & params)
765 params = InsetCommandParams();
769 istringstream data(in);
775 if (!lex || name != name_)
776 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
778 // This is part of the inset proper that is usually swallowed
779 // by LyXText::readInset
782 if (!lex || id != "Include")
783 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
785 InsetInclude inset(params);
787 params = inset.params();
792 InsetIncludeMailer::params2string(InsetCommandParams const & params)
794 InsetInclude inset(params);
796 data << name_ << ' ';
798 data << "\\end_inset\n";