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::latex_path;
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;
81 namespace fs = boost::filesystem;
83 extern BufferList bufferlist;
88 string const uniqueID()
90 static unsigned int seed = 1000;
91 return "file" + convert<string>(++seed);
97 InsetInclude::InsetInclude(InsetCommandParams const & p)
98 : params_(p), include_label(uniqueID()),
99 preview_(new RenderMonitoredPreview(this)),
102 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
106 InsetInclude::InsetInclude(InsetInclude const & other)
108 params_(other.params_),
109 include_label(other.include_label),
110 preview_(new RenderMonitoredPreview(this)),
113 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
117 InsetInclude::~InsetInclude()
119 InsetIncludeMailer(*this).hideDialog();
123 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
125 switch (cmd.action) {
127 case LFUN_INSET_MODIFY: {
128 InsetCommandParams p;
129 InsetIncludeMailer::string2params(cmd.argument, p);
130 if (!p.getCmdName().empty()) {
131 set(p, cur.buffer());
137 case LFUN_INSET_DIALOG_UPDATE:
138 InsetIncludeMailer(*this).updateDialog(&cur.bv());
141 case LFUN_MOUSE_RELEASE:
142 case LFUN_INSET_DIALOG_SHOW:
143 InsetIncludeMailer(*this).showDialog(&cur.bv());
147 InsetBase::doDispatch(cur, cmd);
153 InsetCommandParams const & InsetInclude::params() const
161 /// the type of inclusion
170 Types type(InsetCommandParams const & params)
172 string const command_name = params.getCmdName();
174 if (command_name == "input")
176 if (command_name == "verbatiminput")
178 if (command_name == "verbatiminput*")
184 bool isVerbatim(InsetCommandParams const & params)
186 string const command_name = params.getCmdName();
187 return command_name == "verbatiminput" ||
188 command_name == "verbatiminput*";
192 string const masterFilename(Buffer const & buffer)
194 return buffer.getMasterBuffer()->fileName();
198 string const parentFilename(Buffer const & buffer)
200 return buffer.fileName();
204 string const includedFilename(Buffer const & buffer,
205 InsetCommandParams const & params)
207 return MakeAbsPath(params.getContents(),
208 OnlyPath(parentFilename(buffer)));
212 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
217 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
222 if (preview_->monitoring())
223 preview_->stopMonitoring();
225 if (type(params_) == INPUT)
226 add_preview(*preview_, *this, buffer);
230 auto_ptr<InsetBase> InsetInclude::doClone() const
232 return auto_ptr<InsetBase>(new InsetInclude(*this));
236 void InsetInclude::write(Buffer const &, ostream & os) const
242 void InsetInclude::write(ostream & os) const
244 os << "Include " << params_.getCommand() << '\n'
245 << "preview " << convert<string>(params_.preview()) << '\n';
249 void InsetInclude::read(Buffer const &, LyXLex & lex)
255 void InsetInclude::read(LyXLex & lex)
261 string const InsetInclude::getScreenLabel(Buffer const &) const
265 switch (type(params_)) {
266 case INPUT: temp += _("Input"); break;
267 case VERB: temp += _("Verbatim Input"); break;
268 case VERBAST: temp += _("Verbatim Input*"); break;
269 case INCLUDE: temp += _("Include"); break;
274 if (params_.getContents().empty())
277 temp += OnlyFilename(params_.getContents());
285 /// return true if the file is or got loaded.
286 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
288 if (isVerbatim(params))
291 string const included_file = includedFilename(buffer, params);
292 if (!IsLyXFilename(included_file))
295 Buffer * buf = bufferlist.getBuffer(included_file);
297 // the readonly flag can/will be wrong, not anymore I think.
298 if (!fs::exists(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 incfile = latex_path(incfile);
390 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
391 } else if (type(params_) == INPUT) {
392 runparams.exportdata->addExternalFile("latex", writefile,
395 // \input wants file with extension (default is .tex)
396 if (!IsLyXFilename(included_file)) {
397 incfile = latex_path(incfile);
398 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
400 incfile = ChangeExtension(incfile, ".tex");
401 incfile = latex_path(incfile);
402 os << '\\' << params_.getCmdName() << '{'
407 runparams.exportdata->addExternalFile("latex", writefile,
410 // \include don't want extension and demands that the
411 // file really have .tex
412 incfile = ChangeExtension(incfile, string());
413 incfile = latex_path(incfile);
414 os << '\\' << params_.getCmdName() << '{'
423 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
424 OutputParams const &) const
426 if (isVerbatim(params_))
427 os << GetFileContents(includedFilename(buffer, params_));
432 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
433 OutputParams const & runparams) const
435 string incfile(params_.getContents());
437 // Do nothing if no file name has been specified
441 string const included_file = includedFilename(buffer, params_);
443 // write it to a file (so far the complete file)
444 string const exportfile = ChangeExtension(incfile, ".sgml");
445 string writefile = ChangeExtension(included_file, ".sgml");
447 if (loadIfNeeded(buffer, params_)) {
448 Buffer * tmp = bufferlist.getBuffer(included_file);
450 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
451 buffer.getMasterBuffer()->temppath());
455 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
456 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
457 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
459 tmp->makeLinuxDocFile(writefile, runparams, true);
462 if (isVerbatim(params_)) {
464 << GetFileContents(included_file)
467 runparams.exportdata->addExternalFile("linuxdoc", writefile,
469 os << '&' << include_label << ';';
476 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
477 OutputParams const & runparams) const
479 string incfile(params_.getContents());
481 // Do nothing if no file name has been specified
485 string const included_file = includedFilename(buffer, params_);
487 // write it to a file (so far the complete file)
488 string const exportfile = ChangeExtension(incfile, ".sgml");
489 string writefile = ChangeExtension(included_file, ".sgml");
491 if (loadIfNeeded(buffer, params_)) {
492 Buffer * tmp = bufferlist.getBuffer(included_file);
494 string const mangled = FileName(writefile).mangledFilename();
495 writefile = MakeAbsPath(mangled,
496 buffer.getMasterBuffer()->temppath());
500 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
501 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
502 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
504 tmp->makeDocBookFile(writefile, runparams, true);
507 runparams.exportdata->addExternalFile("docbook", writefile,
509 runparams.exportdata->addExternalFile("docbook-xml", writefile,
512 if (isVerbatim(params_)) {
513 os << "<inlinegraphic fileref=\""
514 << '&' << include_label << ';'
515 << "\" format=\"linespecific\">";
517 os << '&' << include_label << ';';
523 void InsetInclude::validate(LaTeXFeatures & features) const
525 string incfile(params_.getContents());
528 Buffer const & buffer = features.buffer();
530 string const included_file = includedFilename(buffer, params_);
532 if (IsLyXFilename(included_file))
533 writefile = ChangeExtension(included_file, ".sgml");
535 writefile = included_file;
537 if (!features.nice() && !isVerbatim(params_)) {
538 incfile = FileName(writefile).mangledFilename();
539 writefile = MakeAbsPath(incfile,
540 buffer.getMasterBuffer()->temppath());
543 features.includeFile(include_label, writefile);
545 if (isVerbatim(params_))
546 features.require("verbatim");
548 // Here we must do the fun stuff...
549 // Load the file in the include if it needs
551 if (loadIfNeeded(buffer, params_)) {
553 Buffer * const tmp = bufferlist.getBuffer(included_file);
555 // We must temporarily change features.buffer,
556 // otherwise it would always be the master buffer,
557 // and nested includes would not work.
558 features.setBuffer(*tmp);
559 tmp->validate(features);
560 features.setBuffer(buffer);
566 void InsetInclude::getLabelList(Buffer const & buffer,
567 std::vector<string> & list) const
569 if (loadIfNeeded(buffer, params_)) {
570 string const included_file = includedFilename(buffer, params_);
571 Buffer * tmp = bufferlist.getBuffer(included_file);
572 tmp->setParentName("");
573 tmp->getLabelList(list);
574 tmp->setParentName(parentFilename(buffer));
579 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
580 std::vector<std::pair<string,string> > & keys) const
582 if (loadIfNeeded(buffer, params_)) {
583 string const included_file = includedFilename(buffer, params_);
584 Buffer * tmp = bufferlist.getBuffer(included_file);
585 tmp->setParentName("");
586 tmp->fillWithBibKeys(keys);
587 tmp->setParentName(parentFilename(buffer));
592 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
594 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
596 bool use_preview = false;
597 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
598 lyx::graphics::PreviewImage const * pimage =
599 preview_->getPreviewImage(*mi.base.bv->buffer());
600 use_preview = pimage && pimage->image();
604 preview_->metrics(mi, dim);
608 button_.update(getScreenLabel(*mi.base.bv->buffer()),
611 button_.metrics(mi, dim);
614 Box b(0, dim.wid, -dim.asc, dim.des);
621 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
623 setPosCache(pi, x, y);
625 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
627 bool use_preview = false;
628 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
629 lyx::graphics::PreviewImage const * pimage =
630 preview_->getPreviewImage(*pi.base.bv->buffer());
631 use_preview = pimage && pimage->image();
635 preview_->draw(pi, x, y);
637 button_.draw(pi, x, y);
640 bool InsetInclude::display() const
642 return type(params_) != INPUT;
651 void InsetInclude::fileChanged() const
653 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
657 Buffer const & buffer = *buffer_ptr;
658 preview_->removePreview(buffer);
659 add_preview(*preview_.get(), *this, buffer);
660 preview_->startLoading(buffer);
666 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
668 string const included_file = includedFilename(buffer, params);
670 return type(params) == INPUT && params.preview() &&
671 IsFileReadable(included_file);
675 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
678 OutputParams runparams;
679 runparams.flavor = OutputParams::LATEX;
680 inset.latex(buffer, os, runparams);
686 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
687 Buffer const & buffer)
689 InsetCommandParams const & params = inset.params();
690 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
691 preview_wanted(params, buffer)) {
692 renderer.setAbsFile(includedFilename(buffer, params));
693 string const snippet = latex_string(inset, buffer);
694 renderer.addPreview(snippet, buffer);
701 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
703 Buffer const & buffer = ploader.buffer();
704 if (preview_wanted(params(), buffer)) {
705 preview_->setAbsFile(includedFilename(buffer, params()));
706 string const snippet = latex_string(*this, buffer);
707 preview_->addPreview(snippet, ploader);
712 string const InsetIncludeMailer::name_("include");
714 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
719 string const InsetIncludeMailer::inset2string(Buffer const &) const
721 return params2string(inset_.params());
725 void InsetIncludeMailer::string2params(string const & in,
726 InsetCommandParams & params)
728 params = InsetCommandParams();
732 istringstream data(in);
738 if (!lex || name != name_)
739 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
741 // This is part of the inset proper that is usually swallowed
742 // by LyXText::readInset
745 if (!lex || id != "Include")
746 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
748 InsetInclude inset(params);
750 params = inset.params();
755 InsetIncludeMailer::params2string(InsetCommandParams const & params)
757 InsetInclude inset(params);
759 data << name_ << ' ';
761 data << "\\end_inset\n";