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"
26 #include "LaTeXFeatures.h"
30 #include "metricsinfo.h"
31 #include "outputparams.h"
33 #include "frontends/Alert.h"
34 #include "frontends/LyXView.h"
35 #include "frontends/Painter.h"
37 #include "graphics/PreviewImage.h"
38 #include "graphics/PreviewLoader.h"
40 #include "insets/render_preview.h"
42 #include "support/FileInfo.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/tostr.h"
49 #include <boost/bind.hpp>
51 #include "support/std_ostream.h"
55 using lyx::support::AddName;
56 using lyx::support::AbsolutePath;
57 using lyx::support::bformat;
58 using lyx::support::ChangeExtension;
59 using lyx::support::contains;
60 using lyx::support::copy;
61 using lyx::support::FileInfo;
62 using lyx::support::FileName;
63 using lyx::support::GetFileContents;
64 using lyx::support::IsFileReadable;
65 using lyx::support::IsLyXFilename;
66 using lyx::support::MakeAbsPath;
67 using lyx::support::MakeDisplayPath;
68 using lyx::support::MakeRelPath;
69 using lyx::support::OnlyFilename;
70 using lyx::support::OnlyPath;
71 using lyx::support::subst;
72 using lyx::support::sum;
77 using std::istringstream;
79 using std::ostringstream;
82 extern BufferList bufferlist;
87 string const uniqueID()
89 static unsigned int seed = 1000;
90 return "file" + tostr(++seed);
96 InsetInclude::InsetInclude(InsetCommandParams const & p)
97 : params_(p), include_label(uniqueID()),
98 preview_(new RenderMonitoredPreview(this)),
101 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
105 InsetInclude::InsetInclude(InsetInclude const & other)
107 params_(other.params_),
108 include_label(other.include_label),
109 preview_(new RenderMonitoredPreview(this)),
110 set_label_(other.set_label_)
112 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
116 InsetInclude::~InsetInclude()
118 InsetIncludeMailer(*this).hideDialog();
122 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
124 switch (cmd.action) {
126 case LFUN_INSET_MODIFY: {
127 InsetCommandParams p;
128 InsetIncludeMailer::string2params(cmd.argument, p);
129 if (!p.getCmdName().empty()) {
130 set(p, cur.buffer());
136 case LFUN_INSET_DIALOG_UPDATE:
137 InsetIncludeMailer(*this).updateDialog(&cur.bv());
140 case LFUN_MOUSE_RELEASE:
141 case LFUN_INSET_DIALOG_SHOW:
142 InsetIncludeMailer(*this).showDialog(&cur.bv());
146 InsetBase::doDispatch(cur, cmd);
152 InsetCommandParams const & InsetInclude::params() const
160 /// the type of inclusion
169 Types type(InsetCommandParams const & params)
171 string const command_name = params.getCmdName();
173 if (command_name == "input")
175 if (command_name == "verbatiminput")
177 if (command_name == "verbatiminput*")
183 bool isVerbatim(InsetCommandParams const & params)
185 string const command_name = params.getCmdName();
186 return command_name == "verbatiminput" ||
187 command_name == "verbatiminput*";
191 string const masterFilename(Buffer const & buffer)
193 return buffer.getMasterBuffer()->fileName();
197 string const parentFilename(Buffer const & buffer)
199 return buffer.fileName();
203 string const includedFilename(Buffer const & buffer,
204 InsetCommandParams const & params)
206 return MakeAbsPath(params.getContents(),
207 OnlyPath(parentFilename(buffer)));
211 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
216 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
221 if (preview_->monitoring())
222 preview_->stopMonitoring();
224 if (type(params_) == INPUT)
225 add_preview(*preview_, *this, buffer);
229 auto_ptr<InsetBase> InsetInclude::doClone() const
231 return auto_ptr<InsetBase>(new InsetInclude(*this));
235 void InsetInclude::write(Buffer const &, ostream & os) const
241 void InsetInclude::write(ostream & os) const
243 os << "Include " << params_.getCommand() << '\n'
244 << "preview " << tostr(params_.preview()) << '\n';
248 void InsetInclude::read(Buffer const &, LyXLex & lex)
254 void InsetInclude::read(LyXLex & lex)
260 string const InsetInclude::getScreenLabel(Buffer const &) const
264 switch (type(params_)) {
265 case INPUT: temp += _("Input"); break;
266 case VERB: temp += _("Verbatim Input"); break;
267 case VERBAST: temp += _("Verbatim Input*"); break;
268 case INCLUDE: temp += _("Include"); break;
273 if (params_.getContents().empty())
276 temp += OnlyFilename(params_.getContents());
284 /// return true if the file is or got loaded.
285 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
287 if (isVerbatim(params))
290 string const included_file = includedFilename(buffer, params);
291 if (!IsLyXFilename(included_file))
294 Buffer * buf = bufferlist.getBuffer(included_file);
296 // the readonly flag can/will be wrong, not anymore I think.
297 FileInfo finfo(included_file);
300 buf = bufferlist.newBuffer(included_file);
301 if (!loadLyXFile(buf, included_file))
305 buf->setParentName(parentFilename(buffer));
313 int InsetInclude::latex(Buffer const & buffer, ostream & os,
314 OutputParams const & runparams) const
316 string incfile(params_.getContents());
318 // Do nothing if no file name has been specified
322 string const included_file = includedFilename(buffer, params_);
323 Buffer const * const m_buffer = buffer.getMasterBuffer();
325 // if incfile is relative, make it relative to the master
327 if (!AbsolutePath(incfile)) {
328 incfile = MakeRelPath(included_file,
329 m_buffer->filePath());
332 // write it to a file (so far the complete file)
333 string const exportfile = ChangeExtension(incfile, ".tex");
334 string const mangled = FileName(ChangeExtension(included_file,
335 ".tex")).mangledFilename();
336 string const writefile = MakeAbsPath(mangled, m_buffer->temppath());
340 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
341 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
342 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
344 if (loadIfNeeded(buffer, params_)) {
345 Buffer * tmp = bufferlist.getBuffer(included_file);
347 if (tmp->params().textclass != m_buffer->params().textclass) {
348 string text = bformat(_("Included file `%1$s'\n"
349 "has textclass `%2$s'\n"
350 "while parent file has textclass `%3$s'."),
351 MakeDisplayPath(included_file),
352 tmp->params().getLyXTextClass().name(),
353 m_buffer->params().getLyXTextClass().name());
354 Alert::warning(_("Different textclasses"), text);
358 tmp->markDepClean(m_buffer->temppath());
361 #warning Second argument is irrelevant!
362 // since only_body is true, makeLaTeXFile will not look at second
363 // argument. Should we set it to string(), or should makeLaTeXFile
364 // make use of it somehow? (JMarc 20031002)
366 tmp->makeLaTeXFile(writefile,
367 OnlyPath(masterFilename(buffer)),
370 // Copy the file to the temp dir, so that .aux files etc.
371 // are not created in the original dir. Files included by
372 // this file will be found via input@path, see ../buffer.C.
373 unsigned long const checksum_in = sum(included_file);
374 unsigned long const checksum_out = sum(writefile);
376 if (checksum_in != checksum_out) {
377 if (!copy(included_file, writefile)) {
379 << bformat(_("Could not copy the file\n%1$s\n"
380 "into the temporary directory."),
388 if (isVerbatim(params_)) {
389 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
390 } else if (type(params_) == INPUT) {
391 runparams.exportdata->addExternalFile("latex", writefile,
394 // \input wants file with extension (default is .tex)
395 if (!IsLyXFilename(included_file)) {
396 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
398 os << '\\' << params_.getCmdName() << '{'
399 << ChangeExtension(incfile, ".tex")
403 runparams.exportdata->addExternalFile("latex", writefile,
406 // \include don't want extension and demands that the
407 // file really have .tex
408 os << '\\' << params_.getCmdName() << '{'
409 << ChangeExtension(incfile, string())
417 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
418 OutputParams const &) const
420 if (isVerbatim(params_))
421 os << GetFileContents(includedFilename(buffer, params_));
426 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
427 OutputParams const & runparams) const
429 string incfile(params_.getContents());
431 // Do nothing if no file name has been specified
435 string const included_file = includedFilename(buffer, params_);
437 // write it to a file (so far the complete file)
438 string const exportfile = ChangeExtension(incfile, ".sgml");
439 string writefile = ChangeExtension(included_file, ".sgml");
441 if (loadIfNeeded(buffer, params_)) {
442 Buffer * tmp = bufferlist.getBuffer(included_file);
444 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
445 buffer.getMasterBuffer()->temppath());
449 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
450 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
451 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
453 tmp->makeLinuxDocFile(writefile, runparams, true);
456 if (isVerbatim(params_)) {
458 << GetFileContents(included_file)
461 runparams.exportdata->addExternalFile("linuxdoc", writefile,
463 os << '&' << include_label << ';';
470 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
471 OutputParams const & runparams) const
473 string incfile(params_.getContents());
475 // Do nothing if no file name has been specified
479 string const included_file = includedFilename(buffer, params_);
481 // write it to a file (so far the complete file)
482 string const exportfile = ChangeExtension(incfile, ".sgml");
483 string writefile = ChangeExtension(included_file, ".sgml");
485 if (loadIfNeeded(buffer, params_)) {
486 Buffer * tmp = bufferlist.getBuffer(included_file);
488 string const mangled = FileName(writefile).mangledFilename();
489 writefile = MakeAbsPath(mangled,
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->makeDocBookFile(writefile, runparams, true);
501 runparams.exportdata->addExternalFile("docbook", writefile,
503 runparams.exportdata->addExternalFile("docbook-xml", writefile,
506 if (isVerbatim(params_)) {
507 os << "<inlinegraphic fileref=\""
508 << '&' << include_label << ';'
509 << "\" format=\"linespecific\">";
511 os << '&' << include_label << ';';
517 void InsetInclude::validate(LaTeXFeatures & features) const
519 string incfile(params_.getContents());
522 Buffer const & buffer = features.buffer();
524 string const included_file = includedFilename(buffer, params_);
526 if (IsLyXFilename(included_file))
527 writefile = ChangeExtension(included_file, ".sgml");
529 writefile = included_file;
531 if (!features.nice() && !isVerbatim(params_)) {
532 incfile = FileName(writefile).mangledFilename();
533 writefile = MakeAbsPath(incfile,
534 buffer.getMasterBuffer()->temppath());
537 features.includeFile(include_label, writefile);
539 if (isVerbatim(params_))
540 features.require("verbatim");
542 // Here we must do the fun stuff...
543 // Load the file in the include if it needs
545 if (loadIfNeeded(buffer, params_)) {
547 Buffer * const tmp = bufferlist.getBuffer(included_file);
549 // We must temporarily change features.buffer,
550 // otherwise it would always be the master buffer,
551 // and nested includes would not work.
552 features.setBuffer(*tmp);
553 tmp->validate(features);
554 features.setBuffer(buffer);
560 void InsetInclude::getLabelList(Buffer const & buffer,
561 std::vector<string> & list) const
563 if (loadIfNeeded(buffer, params_)) {
564 string const included_file = includedFilename(buffer, params_);
565 Buffer * tmp = bufferlist.getBuffer(included_file);
566 tmp->setParentName("");
567 tmp->getLabelList(list);
568 tmp->setParentName(parentFilename(buffer));
573 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
574 std::vector<std::pair<string,string> > & keys) const
576 if (loadIfNeeded(buffer, params_)) {
577 string const included_file = includedFilename(buffer, params_);
578 Buffer * tmp = bufferlist.getBuffer(included_file);
579 tmp->setParentName("");
580 tmp->fillWithBibKeys(keys);
581 tmp->setParentName(parentFilename(buffer));
586 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
588 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
590 bool use_preview = false;
591 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
592 lyx::graphics::PreviewImage const * pimage =
593 preview_->getPreviewImage(*mi.base.bv->buffer());
594 use_preview = pimage && pimage->image();
598 preview_->metrics(mi, dim);
602 button_.update(getScreenLabel(*mi.base.bv->buffer()),
605 button_.metrics(mi, dim);
608 Box b(0, dim.wid, -dim.asc, dim.des);
615 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
617 setPosCache(pi, x, y);
619 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
621 bool use_preview = false;
622 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
623 lyx::graphics::PreviewImage const * pimage =
624 preview_->getPreviewImage(*pi.base.bv->buffer());
625 use_preview = pimage && pimage->image();
629 preview_->draw(pi, x, y);
631 button_.draw(pi, x, y);
634 bool InsetInclude::display() const
636 return type(params_) != INPUT;
645 void InsetInclude::fileChanged() const
647 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
651 Buffer const & buffer = *buffer_ptr;
652 preview_->removePreview(buffer);
653 add_preview(*preview_.get(), *this, buffer);
654 preview_->startLoading(buffer);
660 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
662 string const included_file = includedFilename(buffer, params);
664 return type(params) == INPUT && params.preview() &&
665 IsFileReadable(included_file);
669 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
672 OutputParams runparams;
673 runparams.flavor = OutputParams::LATEX;
674 inset.latex(buffer, os, runparams);
680 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
681 Buffer const & buffer)
683 InsetCommandParams const & params = inset.params();
684 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
685 preview_wanted(params, buffer)) {
686 renderer.setAbsFile(includedFilename(buffer, params));
687 string const snippet = latex_string(inset, buffer);
688 renderer.addPreview(snippet, buffer);
695 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
697 Buffer const & buffer = ploader.buffer();
698 if (preview_wanted(params(), buffer)) {
699 preview_->setAbsFile(includedFilename(buffer, params()));
700 string const snippet = latex_string(*this, buffer);
701 preview_->addPreview(snippet, ploader);
706 string const InsetIncludeMailer::name_("include");
708 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
713 string const InsetIncludeMailer::inset2string(Buffer const &) const
715 return params2string(inset_.params());
719 void InsetIncludeMailer::string2params(string const & in,
720 InsetCommandParams & params)
722 params = InsetCommandParams();
726 istringstream data(in);
732 if (!lex || name != name_)
733 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
735 // This is part of the inset proper that is usually swallowed
736 // by LyXText::readInset
739 if (!lex || id != "Include")
740 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
742 InsetInclude inset(params);
744 params = inset.params();
749 InsetIncludeMailer::params2string(InsetCommandParams const & params)
751 InsetInclude inset(params);
753 data << name_ << ' ';
755 data << "\\end_inset\n";