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());
138 case LFUN_INSET_DIALOG_UPDATE:
139 InsetIncludeMailer(*this).updateDialog(&cur.bv());
142 case LFUN_MOUSE_RELEASE:
143 case LFUN_INSET_DIALOG_SHOW:
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:
161 case LFUN_INSET_DIALOG_SHOW:
166 return InsetBase::getStatus(cur, cmd, flag);
171 InsetCommandParams const & InsetInclude::params() const
179 /// the type of inclusion
188 Types type(InsetCommandParams const & params)
190 string const command_name = params.getCmdName();
192 if (command_name == "input")
194 if (command_name == "verbatiminput")
196 if (command_name == "verbatiminput*")
202 bool isVerbatim(InsetCommandParams const & params)
204 string const command_name = params.getCmdName();
205 return command_name == "verbatiminput" ||
206 command_name == "verbatiminput*";
210 string const masterFilename(Buffer const & buffer)
212 return buffer.getMasterBuffer()->fileName();
216 string const parentFilename(Buffer const & buffer)
218 return buffer.fileName();
222 string const includedFilename(Buffer const & buffer,
223 InsetCommandParams const & params)
225 return MakeAbsPath(params.getContents(),
226 OnlyPath(parentFilename(buffer)));
230 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
235 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
240 if (preview_->monitoring())
241 preview_->stopMonitoring();
243 if (type(params_) == INPUT)
244 add_preview(*preview_, *this, buffer);
248 auto_ptr<InsetBase> InsetInclude::doClone() const
250 return auto_ptr<InsetBase>(new InsetInclude(*this));
254 void InsetInclude::write(Buffer const &, ostream & os) const
260 void InsetInclude::write(ostream & os) const
262 os << "Include " << params_.getCommand() << '\n'
263 << "preview " << convert<string>(params_.preview()) << '\n';
267 void InsetInclude::read(Buffer const &, LyXLex & lex)
273 void InsetInclude::read(LyXLex & lex)
279 string const InsetInclude::getScreenLabel(Buffer const &) const
283 switch (type(params_)) {
284 case INPUT: temp += _("Input"); break;
285 case VERB: temp += _("Verbatim Input"); break;
286 case VERBAST: temp += _("Verbatim Input*"); break;
287 case INCLUDE: temp += _("Include"); break;
292 if (params_.getContents().empty())
295 temp += OnlyFilename(params_.getContents());
303 /// return true if the file is or got loaded.
304 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
306 if (isVerbatim(params))
309 string const included_file = includedFilename(buffer, params);
310 if (!IsLyXFilename(included_file))
313 Buffer * buf = bufferlist.getBuffer(included_file);
315 // the readonly flag can/will be wrong, not anymore I think.
316 if (!fs::exists(included_file))
318 buf = bufferlist.newBuffer(included_file);
319 if (!loadLyXFile(buf, included_file))
323 buf->setParentName(parentFilename(buffer));
331 int InsetInclude::latex(Buffer const & buffer, ostream & os,
332 OutputParams const & runparams) const
334 string incfile(params_.getContents());
336 // Do nothing if no file name has been specified
340 string const included_file = includedFilename(buffer, params_);
341 Buffer const * const m_buffer = buffer.getMasterBuffer();
343 // if incfile is relative, make it relative to the master
345 if (!AbsolutePath(incfile)) {
346 incfile = MakeRelPath(included_file,
347 m_buffer->filePath());
350 // write it to a file (so far the complete file)
351 string const exportfile = ChangeExtension(incfile, ".tex");
352 string const mangled = FileName(ChangeExtension(included_file,
353 ".tex")).mangledFilename();
354 string const writefile = MakeAbsPath(mangled, m_buffer->temppath());
358 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
359 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
360 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
362 if (loadIfNeeded(buffer, params_)) {
363 Buffer * tmp = bufferlist.getBuffer(included_file);
365 if (tmp->params().textclass != m_buffer->params().textclass) {
366 string text = bformat(_("Included file `%1$s'\n"
367 "has textclass `%2$s'\n"
368 "while parent file has textclass `%3$s'."),
369 MakeDisplayPath(included_file),
370 tmp->params().getLyXTextClass().name(),
371 m_buffer->params().getLyXTextClass().name());
372 Alert::warning(_("Different textclasses"), text);
376 tmp->markDepClean(m_buffer->temppath());
379 #warning Second argument is irrelevant!
380 // since only_body is true, makeLaTeXFile will not look at second
381 // argument. Should we set it to string(), or should makeLaTeXFile
382 // make use of it somehow? (JMarc 20031002)
384 tmp->makeLaTeXFile(writefile,
385 OnlyPath(masterFilename(buffer)),
388 // Copy the file to the temp dir, so that .aux files etc.
389 // are not created in the original dir. Files included by
390 // this file will be found via input@path, see ../buffer.C.
391 unsigned long const checksum_in = sum(included_file);
392 unsigned long const checksum_out = sum(writefile);
394 if (checksum_in != checksum_out) {
395 if (!copy(included_file, writefile)) {
397 << bformat(_("Could not copy the file\n%1$s\n"
398 "into the temporary directory."),
406 if (isVerbatim(params_)) {
407 incfile = latex_path(incfile);
408 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
409 } else if (type(params_) == INPUT) {
410 runparams.exportdata->addExternalFile("latex", writefile,
413 // \input wants file with extension (default is .tex)
414 if (!IsLyXFilename(included_file)) {
415 incfile = latex_path(incfile);
416 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
418 incfile = ChangeExtension(incfile, ".tex");
419 incfile = latex_path(incfile);
420 os << '\\' << params_.getCmdName() << '{'
425 runparams.exportdata->addExternalFile("latex", writefile,
428 // \include don't want extension and demands that the
429 // file really have .tex
430 incfile = ChangeExtension(incfile, string());
431 incfile = latex_path(incfile);
432 os << '\\' << params_.getCmdName() << '{'
441 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
442 OutputParams const &) const
444 if (isVerbatim(params_))
445 os << GetFileContents(includedFilename(buffer, params_));
450 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
451 OutputParams const & runparams) const
453 string incfile(params_.getContents());
455 // Do nothing if no file name has been specified
459 string const included_file = includedFilename(buffer, params_);
461 // write it to a file (so far the complete file)
462 string const exportfile = ChangeExtension(incfile, ".sgml");
463 string writefile = ChangeExtension(included_file, ".sgml");
465 if (loadIfNeeded(buffer, params_)) {
466 Buffer * tmp = bufferlist.getBuffer(included_file);
468 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
469 buffer.getMasterBuffer()->temppath());
473 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
474 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
475 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
477 tmp->makeLinuxDocFile(writefile, runparams, true);
480 if (isVerbatim(params_)) {
482 << GetFileContents(included_file)
485 runparams.exportdata->addExternalFile("linuxdoc", writefile,
487 os << '&' << include_label << ';';
494 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
495 OutputParams const & runparams) const
497 string incfile(params_.getContents());
499 // Do nothing if no file name has been specified
503 string const included_file = includedFilename(buffer, params_);
505 // write it to a file (so far the complete file)
506 string const exportfile = ChangeExtension(incfile, ".sgml");
507 string writefile = ChangeExtension(included_file, ".sgml");
509 if (loadIfNeeded(buffer, params_)) {
510 Buffer * tmp = bufferlist.getBuffer(included_file);
512 string const mangled = FileName(writefile).mangledFilename();
513 writefile = MakeAbsPath(mangled,
514 buffer.getMasterBuffer()->temppath());
518 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
519 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
520 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
522 tmp->makeDocBookFile(writefile, runparams, true);
525 runparams.exportdata->addExternalFile("docbook", writefile,
527 runparams.exportdata->addExternalFile("docbook-xml", writefile,
530 if (isVerbatim(params_)) {
531 os << "<inlinegraphic fileref=\""
532 << '&' << include_label << ';'
533 << "\" format=\"linespecific\">";
535 os << '&' << include_label << ';';
541 void InsetInclude::validate(LaTeXFeatures & features) const
543 string incfile(params_.getContents());
546 Buffer const & buffer = features.buffer();
548 string const included_file = includedFilename(buffer, params_);
550 if (IsLyXFilename(included_file))
551 writefile = ChangeExtension(included_file, ".sgml");
553 writefile = included_file;
555 if (!features.nice() && !isVerbatim(params_)) {
556 incfile = FileName(writefile).mangledFilename();
557 writefile = MakeAbsPath(incfile,
558 buffer.getMasterBuffer()->temppath());
561 features.includeFile(include_label, writefile);
563 if (isVerbatim(params_))
564 features.require("verbatim");
566 // Here we must do the fun stuff...
567 // Load the file in the include if it needs
569 if (loadIfNeeded(buffer, params_)) {
571 Buffer * const tmp = bufferlist.getBuffer(included_file);
573 // We must temporarily change features.buffer,
574 // otherwise it would always be the master buffer,
575 // and nested includes would not work.
576 features.setBuffer(*tmp);
577 tmp->validate(features);
578 features.setBuffer(buffer);
584 void InsetInclude::getLabelList(Buffer const & buffer,
585 std::vector<string> & list) const
587 if (loadIfNeeded(buffer, params_)) {
588 string const included_file = includedFilename(buffer, params_);
589 Buffer * tmp = bufferlist.getBuffer(included_file);
590 tmp->setParentName("");
591 tmp->getLabelList(list);
592 tmp->setParentName(parentFilename(buffer));
597 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
598 std::vector<std::pair<string,string> > & keys) const
600 if (loadIfNeeded(buffer, params_)) {
601 string const included_file = includedFilename(buffer, params_);
602 Buffer * tmp = bufferlist.getBuffer(included_file);
603 tmp->setParentName("");
604 tmp->fillWithBibKeys(keys);
605 tmp->setParentName(parentFilename(buffer));
610 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
612 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
614 bool use_preview = false;
615 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
616 lyx::graphics::PreviewImage const * pimage =
617 preview_->getPreviewImage(*mi.base.bv->buffer());
618 use_preview = pimage && pimage->image();
622 preview_->metrics(mi, dim);
626 button_.update(getScreenLabel(*mi.base.bv->buffer()),
629 button_.metrics(mi, dim);
632 Box b(0, dim.wid, -dim.asc, dim.des);
639 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
641 setPosCache(pi, x, y);
643 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
645 bool use_preview = false;
646 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
647 lyx::graphics::PreviewImage const * pimage =
648 preview_->getPreviewImage(*pi.base.bv->buffer());
649 use_preview = pimage && pimage->image();
653 preview_->draw(pi, x, y);
655 button_.draw(pi, x, y);
658 bool InsetInclude::display() const
660 return type(params_) != INPUT;
669 void InsetInclude::fileChanged() const
671 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
675 Buffer const & buffer = *buffer_ptr;
676 preview_->removePreview(buffer);
677 add_preview(*preview_.get(), *this, buffer);
678 preview_->startLoading(buffer);
684 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
686 string const included_file = includedFilename(buffer, params);
688 return type(params) == INPUT && params.preview() &&
689 IsFileReadable(included_file);
693 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
696 OutputParams runparams;
697 runparams.flavor = OutputParams::LATEX;
698 inset.latex(buffer, os, runparams);
704 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
705 Buffer const & buffer)
707 InsetCommandParams const & params = inset.params();
708 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
709 preview_wanted(params, buffer)) {
710 renderer.setAbsFile(includedFilename(buffer, params));
711 string const snippet = latex_string(inset, buffer);
712 renderer.addPreview(snippet, buffer);
719 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
721 Buffer const & buffer = ploader.buffer();
722 if (preview_wanted(params(), buffer)) {
723 preview_->setAbsFile(includedFilename(buffer, params()));
724 string const snippet = latex_string(*this, buffer);
725 preview_->addPreview(snippet, ploader);
730 string const InsetIncludeMailer::name_("include");
732 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
737 string const InsetIncludeMailer::inset2string(Buffer const &) const
739 return params2string(inset_.params());
743 void InsetIncludeMailer::string2params(string const & in,
744 InsetCommandParams & params)
746 params = InsetCommandParams();
750 istringstream data(in);
756 if (!lex || name != name_)
757 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
759 // This is part of the inset proper that is usually swallowed
760 // by LyXText::readInset
763 if (!lex || id != "Include")
764 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
766 InsetInclude inset(params);
768 params = inset.params();
773 InsetIncludeMailer::params2string(InsetCommandParams const & params)
775 InsetInclude inset(params);
777 data << name_ << ' ';
779 data << "\\end_inset\n";