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 (runparams.inComment)
363 // Don't try to load or copy the file
365 else if (loadIfNeeded(buffer, params_)) {
366 Buffer * tmp = bufferlist.getBuffer(included_file);
368 if (tmp->params().textclass != m_buffer->params().textclass) {
369 string text = bformat(_("Included file `%1$s'\n"
370 "has textclass `%2$s'\n"
371 "while parent file has textclass `%3$s'."),
372 MakeDisplayPath(included_file),
373 tmp->params().getLyXTextClass().name(),
374 m_buffer->params().getLyXTextClass().name());
375 Alert::warning(_("Different textclasses"), text);
379 tmp->markDepClean(m_buffer->temppath());
382 #warning handle non existing files
383 #warning Second argument is irrelevant!
384 // since only_body is true, makeLaTeXFile will not look at second
385 // argument. Should we set it to string(), or should makeLaTeXFile
386 // make use of it somehow? (JMarc 20031002)
388 tmp->makeLaTeXFile(writefile,
389 OnlyPath(masterFilename(buffer)),
392 // Copy the file to the temp dir, so that .aux files etc.
393 // are not created in the original dir. Files included by
394 // this file will be found via input@path, see ../buffer.C.
395 unsigned long const checksum_in = sum(included_file);
396 unsigned long const checksum_out = sum(writefile);
398 if (checksum_in != checksum_out) {
399 if (!copy(included_file, writefile)) {
401 << bformat(_("Could not copy the file\n%1$s\n"
402 "into the temporary directory."),
410 if (isVerbatim(params_)) {
411 incfile = latex_path(incfile);
412 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
413 } else if (type(params_) == INPUT) {
414 runparams.exportdata->addExternalFile("latex", writefile,
417 // \input wants file with extension (default is .tex)
418 if (!IsLyXFilename(included_file)) {
419 incfile = latex_path(incfile);
420 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
422 incfile = ChangeExtension(incfile, ".tex");
423 incfile = latex_path(incfile);
424 os << '\\' << params_.getCmdName() << '{'
429 runparams.exportdata->addExternalFile("latex", writefile,
432 // \include don't want extension and demands that the
433 // file really have .tex
434 incfile = ChangeExtension(incfile, string());
435 incfile = latex_path(incfile);
436 os << '\\' << params_.getCmdName() << '{'
445 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
446 OutputParams const &) const
448 if (isVerbatim(params_))
449 os << GetFileContents(includedFilename(buffer, params_));
454 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
455 OutputParams const & runparams) const
457 string incfile(params_.getContents());
459 // Do nothing if no file name has been specified
463 string const included_file = includedFilename(buffer, params_);
465 // write it to a file (so far the complete file)
466 string const exportfile = ChangeExtension(incfile, ".sgml");
467 string writefile = ChangeExtension(included_file, ".sgml");
469 if (loadIfNeeded(buffer, params_)) {
470 Buffer * tmp = bufferlist.getBuffer(included_file);
472 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
473 buffer.getMasterBuffer()->temppath());
477 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
478 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
479 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
481 tmp->makeLinuxDocFile(writefile, runparams, true);
484 if (isVerbatim(params_)) {
486 << GetFileContents(included_file)
489 runparams.exportdata->addExternalFile("linuxdoc", writefile,
491 os << '&' << include_label << ';';
498 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
499 OutputParams const & runparams) const
501 string incfile(params_.getContents());
503 // Do nothing if no file name has been specified
507 string const included_file = includedFilename(buffer, params_);
509 // write it to a file (so far the complete file)
510 string const exportfile = ChangeExtension(incfile, ".sgml");
511 string writefile = ChangeExtension(included_file, ".sgml");
513 if (loadIfNeeded(buffer, params_)) {
514 Buffer * tmp = bufferlist.getBuffer(included_file);
516 string const mangled = FileName(writefile).mangledFilename();
517 writefile = MakeAbsPath(mangled,
518 buffer.getMasterBuffer()->temppath());
522 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
523 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
524 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
526 tmp->makeDocBookFile(writefile, runparams, true);
529 runparams.exportdata->addExternalFile("docbook", writefile,
531 runparams.exportdata->addExternalFile("docbook-xml", writefile,
534 if (isVerbatim(params_)) {
535 os << "<inlinegraphic fileref=\""
536 << '&' << include_label << ';'
537 << "\" format=\"linespecific\">";
539 os << '&' << include_label << ';';
545 void InsetInclude::validate(LaTeXFeatures & features) const
547 string incfile(params_.getContents());
550 Buffer const & buffer = features.buffer();
552 string const included_file = includedFilename(buffer, params_);
554 if (IsLyXFilename(included_file))
555 writefile = ChangeExtension(included_file, ".sgml");
557 writefile = included_file;
559 if (!features.nice() && !isVerbatim(params_)) {
560 incfile = FileName(writefile).mangledFilename();
561 writefile = MakeAbsPath(incfile,
562 buffer.getMasterBuffer()->temppath());
565 features.includeFile(include_label, writefile);
567 if (isVerbatim(params_))
568 features.require("verbatim");
570 // Here we must do the fun stuff...
571 // Load the file in the include if it needs
573 if (loadIfNeeded(buffer, params_)) {
575 Buffer * const tmp = bufferlist.getBuffer(included_file);
577 // We must temporarily change features.buffer,
578 // otherwise it would always be the master buffer,
579 // and nested includes would not work.
580 features.setBuffer(*tmp);
581 tmp->validate(features);
582 features.setBuffer(buffer);
588 void InsetInclude::getLabelList(Buffer const & buffer,
589 std::vector<string> & list) const
591 if (loadIfNeeded(buffer, params_)) {
592 string const included_file = includedFilename(buffer, params_);
593 Buffer * tmp = bufferlist.getBuffer(included_file);
594 tmp->setParentName("");
595 tmp->getLabelList(list);
596 tmp->setParentName(parentFilename(buffer));
601 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
602 std::vector<std::pair<string,string> > & keys) const
604 if (loadIfNeeded(buffer, params_)) {
605 string const included_file = includedFilename(buffer, params_);
606 Buffer * tmp = bufferlist.getBuffer(included_file);
607 tmp->setParentName("");
608 tmp->fillWithBibKeys(keys);
609 tmp->setParentName(parentFilename(buffer));
614 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
616 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
618 bool use_preview = false;
619 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
620 lyx::graphics::PreviewImage const * pimage =
621 preview_->getPreviewImage(*mi.base.bv->buffer());
622 use_preview = pimage && pimage->image();
626 preview_->metrics(mi, dim);
630 button_.update(getScreenLabel(*mi.base.bv->buffer()),
633 button_.metrics(mi, dim);
636 Box b(0, dim.wid, -dim.asc, dim.des);
643 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
645 setPosCache(pi, x, y);
647 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
649 bool use_preview = false;
650 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
651 lyx::graphics::PreviewImage const * pimage =
652 preview_->getPreviewImage(*pi.base.bv->buffer());
653 use_preview = pimage && pimage->image();
657 preview_->draw(pi, x, y);
659 button_.draw(pi, x, y);
662 bool InsetInclude::display() const
664 return type(params_) != INPUT;
673 void InsetInclude::fileChanged() const
675 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
679 Buffer const & buffer = *buffer_ptr;
680 preview_->removePreview(buffer);
681 add_preview(*preview_.get(), *this, buffer);
682 preview_->startLoading(buffer);
688 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
690 string const included_file = includedFilename(buffer, params);
692 return type(params) == INPUT && params.preview() &&
693 IsFileReadable(included_file);
697 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
700 OutputParams runparams;
701 runparams.flavor = OutputParams::LATEX;
702 inset.latex(buffer, os, runparams);
708 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
709 Buffer const & buffer)
711 InsetCommandParams const & params = inset.params();
712 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
713 preview_wanted(params, buffer)) {
714 renderer.setAbsFile(includedFilename(buffer, params));
715 string const snippet = latex_string(inset, buffer);
716 renderer.addPreview(snippet, buffer);
723 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
725 Buffer const & buffer = ploader.buffer();
726 if (preview_wanted(params(), buffer)) {
727 preview_->setAbsFile(includedFilename(buffer, params()));
728 string const snippet = latex_string(*this, buffer);
729 preview_->addPreview(snippet, ploader);
734 string const InsetIncludeMailer::name_("include");
736 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
741 string const InsetIncludeMailer::inset2string(Buffer const &) const
743 return params2string(inset_.params());
747 void InsetIncludeMailer::string2params(string const & in,
748 InsetCommandParams & params)
750 params = InsetCommandParams();
754 istringstream data(in);
760 if (!lex || name != name_)
761 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
763 // This is part of the inset proper that is usually swallowed
764 // by LyXText::readInset
767 if (!lex || id != "Include")
768 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
770 InsetInclude inset(params);
772 params = inset.params();
777 InsetIncludeMailer::params2string(InsetCommandParams const & params)
779 InsetInclude inset(params);
781 data << name_ << ' ';
783 data << "\\end_inset\n";