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/filename.h"
43 #include "support/filetools.h"
44 #include "support/lstrings.h" // contains
45 #include "support/lyxlib.h"
46 #include "support/convert.h"
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.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::FileName;
62 using lyx::support::GetFileContents;
63 using lyx::support::IsFileReadable;
64 using lyx::support::IsLyXFilename;
65 using lyx::support::MakeAbsPath;
66 using lyx::support::MakeDisplayPath;
67 using lyx::support::MakeRelPath;
68 using lyx::support::OnlyFilename;
69 using lyx::support::OnlyPath;
70 using lyx::support::subst;
71 using lyx::support::sum;
76 using std::istringstream;
78 using std::ostringstream;
80 namespace fs = boost::filesystem;
82 extern BufferList bufferlist;
87 string const uniqueID()
89 static unsigned int seed = 1000;
90 return "file" + convert<string>(++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 " << convert<string>(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 if (!fs::exists(included_file))
299 buf = bufferlist.newBuffer(included_file);
300 if (!loadLyXFile(buf, included_file))
304 buf->setParentName(parentFilename(buffer));
312 int InsetInclude::latex(Buffer const & buffer, ostream & os,
313 OutputParams const & runparams) const
315 string incfile(params_.getContents());
317 // Do nothing if no file name has been specified
321 string const included_file = includedFilename(buffer, params_);
322 Buffer const * const m_buffer = buffer.getMasterBuffer();
324 // if incfile is relative, make it relative to the master
326 if (!AbsolutePath(incfile)) {
327 incfile = MakeRelPath(included_file,
328 m_buffer->filePath());
331 // write it to a file (so far the complete file)
332 string const exportfile = ChangeExtension(incfile, ".tex");
333 string const mangled = FileName(ChangeExtension(included_file,
334 ".tex")).mangledFilename();
335 string const writefile = MakeAbsPath(mangled, m_buffer->temppath());
339 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
340 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
341 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
343 if (loadIfNeeded(buffer, params_)) {
344 Buffer * tmp = bufferlist.getBuffer(included_file);
346 if (tmp->params().textclass != m_buffer->params().textclass) {
347 string text = bformat(_("Included file `%1$s'\n"
348 "has textclass `%2$s'\n"
349 "while parent file has textclass `%3$s'."),
350 MakeDisplayPath(included_file),
351 tmp->params().getLyXTextClass().name(),
352 m_buffer->params().getLyXTextClass().name());
353 Alert::warning(_("Different textclasses"), text);
357 tmp->markDepClean(m_buffer->temppath());
360 #warning Second argument is irrelevant!
361 // since only_body is true, makeLaTeXFile will not look at second
362 // argument. Should we set it to string(), or should makeLaTeXFile
363 // make use of it somehow? (JMarc 20031002)
365 tmp->makeLaTeXFile(writefile,
366 OnlyPath(masterFilename(buffer)),
369 // Copy the file to the temp dir, so that .aux files etc.
370 // are not created in the original dir. Files included by
371 // this file will be found via input@path, see ../buffer.C.
372 unsigned long const checksum_in = sum(included_file);
373 unsigned long const checksum_out = sum(writefile);
375 if (checksum_in != checksum_out) {
376 if (!copy(included_file, writefile)) {
378 << bformat(_("Could not copy the file\n%1$s\n"
379 "into the temporary directory."),
387 if (isVerbatim(params_)) {
388 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
389 } else if (type(params_) == INPUT) {
390 runparams.exportdata->addExternalFile("latex", writefile,
393 // \input wants file with extension (default is .tex)
394 if (!IsLyXFilename(included_file)) {
395 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
397 os << '\\' << params_.getCmdName() << '{'
398 << ChangeExtension(incfile, ".tex")
402 runparams.exportdata->addExternalFile("latex", writefile,
405 // \include don't want extension and demands that the
406 // file really have .tex
407 os << '\\' << params_.getCmdName() << '{'
408 << ChangeExtension(incfile, string())
416 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
417 OutputParams const &) const
419 if (isVerbatim(params_))
420 os << GetFileContents(includedFilename(buffer, params_));
425 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
426 OutputParams const & runparams) const
428 string incfile(params_.getContents());
430 // Do nothing if no file name has been specified
434 string const included_file = includedFilename(buffer, params_);
436 // write it to a file (so far the complete file)
437 string const exportfile = ChangeExtension(incfile, ".sgml");
438 string writefile = ChangeExtension(included_file, ".sgml");
440 if (loadIfNeeded(buffer, params_)) {
441 Buffer * tmp = bufferlist.getBuffer(included_file);
443 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
444 buffer.getMasterBuffer()->temppath());
448 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
449 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
450 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
452 tmp->makeLinuxDocFile(writefile, runparams, true);
455 if (isVerbatim(params_)) {
457 << GetFileContents(included_file)
460 runparams.exportdata->addExternalFile("linuxdoc", writefile,
462 os << '&' << include_label << ';';
469 int InsetInclude::docbook(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 string const mangled = FileName(writefile).mangledFilename();
488 writefile = MakeAbsPath(mangled,
489 buffer.getMasterBuffer()->temppath());
493 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
494 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
495 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
497 tmp->makeDocBookFile(writefile, runparams, true);
500 runparams.exportdata->addExternalFile("docbook", writefile,
502 runparams.exportdata->addExternalFile("docbook-xml", writefile,
505 if (isVerbatim(params_)) {
506 os << "<inlinegraphic fileref=\""
507 << '&' << include_label << ';'
508 << "\" format=\"linespecific\">";
510 os << '&' << include_label << ';';
516 void InsetInclude::validate(LaTeXFeatures & features) const
518 string incfile(params_.getContents());
521 Buffer const & buffer = features.buffer();
523 string const included_file = includedFilename(buffer, params_);
525 if (IsLyXFilename(included_file))
526 writefile = ChangeExtension(included_file, ".sgml");
528 writefile = included_file;
530 if (!features.nice() && !isVerbatim(params_)) {
531 incfile = FileName(writefile).mangledFilename();
532 writefile = MakeAbsPath(incfile,
533 buffer.getMasterBuffer()->temppath());
536 features.includeFile(include_label, writefile);
538 if (isVerbatim(params_))
539 features.require("verbatim");
541 // Here we must do the fun stuff...
542 // Load the file in the include if it needs
544 if (loadIfNeeded(buffer, params_)) {
546 Buffer * const tmp = bufferlist.getBuffer(included_file);
548 // We must temporarily change features.buffer,
549 // otherwise it would always be the master buffer,
550 // and nested includes would not work.
551 features.setBuffer(*tmp);
552 tmp->validate(features);
553 features.setBuffer(buffer);
559 void InsetInclude::getLabelList(Buffer const & buffer,
560 std::vector<string> & list) const
562 if (loadIfNeeded(buffer, params_)) {
563 string const included_file = includedFilename(buffer, params_);
564 Buffer * tmp = bufferlist.getBuffer(included_file);
565 tmp->setParentName("");
566 tmp->getLabelList(list);
567 tmp->setParentName(parentFilename(buffer));
572 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
573 std::vector<std::pair<string,string> > & keys) const
575 if (loadIfNeeded(buffer, params_)) {
576 string const included_file = includedFilename(buffer, params_);
577 Buffer * tmp = bufferlist.getBuffer(included_file);
578 tmp->setParentName("");
579 tmp->fillWithBibKeys(keys);
580 tmp->setParentName(parentFilename(buffer));
585 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
587 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
589 bool use_preview = false;
590 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
591 lyx::graphics::PreviewImage const * pimage =
592 preview_->getPreviewImage(*mi.base.bv->buffer());
593 use_preview = pimage && pimage->image();
597 preview_->metrics(mi, dim);
601 button_.update(getScreenLabel(*mi.base.bv->buffer()),
604 button_.metrics(mi, dim);
607 Box b(0, dim.wid, -dim.asc, dim.des);
614 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
616 setPosCache(pi, x, y);
618 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
620 bool use_preview = false;
621 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
622 lyx::graphics::PreviewImage const * pimage =
623 preview_->getPreviewImage(*pi.base.bv->buffer());
624 use_preview = pimage && pimage->image();
628 preview_->draw(pi, x, y);
630 button_.draw(pi, x, y);
633 bool InsetInclude::display() const
635 return type(params_) != INPUT;
644 void InsetInclude::fileChanged() const
646 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
650 Buffer const & buffer = *buffer_ptr;
651 preview_->removePreview(buffer);
652 add_preview(*preview_.get(), *this, buffer);
653 preview_->startLoading(buffer);
659 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
661 string const included_file = includedFilename(buffer, params);
663 return type(params) == INPUT && params.preview() &&
664 IsFileReadable(included_file);
668 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
671 OutputParams runparams;
672 runparams.flavor = OutputParams::LATEX;
673 inset.latex(buffer, os, runparams);
679 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
680 Buffer const & buffer)
682 InsetCommandParams const & params = inset.params();
683 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
684 preview_wanted(params, buffer)) {
685 renderer.setAbsFile(includedFilename(buffer, params));
686 string const snippet = latex_string(inset, buffer);
687 renderer.addPreview(snippet, buffer);
694 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
696 Buffer const & buffer = ploader.buffer();
697 if (preview_wanted(params(), buffer)) {
698 preview_->setAbsFile(includedFilename(buffer, params()));
699 string const snippet = latex_string(*this, buffer);
700 preview_->addPreview(snippet, ploader);
705 string const InsetIncludeMailer::name_("include");
707 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
712 string const InsetIncludeMailer::inset2string(Buffer const &) const
714 return params2string(inset_.params());
718 void InsetIncludeMailer::string2params(string const & in,
719 InsetCommandParams & params)
721 params = InsetCommandParams();
725 istringstream data(in);
731 if (!lex || name != name_)
732 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
734 // This is part of the inset proper that is usually swallowed
735 // by LyXText::readInset
738 if (!lex || id != "Include")
739 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
741 InsetInclude inset(params);
743 params = inset.params();
748 InsetIncludeMailer::params2string(InsetCommandParams const & params)
750 InsetInclude inset(params);
752 data << name_ << ' ';
754 data << "\\end_inset\n";