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::priv_dispatch(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 if (button_.box().contains(cmd.x, cmd.y))
142 InsetIncludeMailer(*this).showDialog(&cur.bv());
145 case LFUN_INSET_DIALOG_SHOW:
146 InsetIncludeMailer(*this).showDialog(&cur.bv());
150 InsetOld::priv_dispatch(cur, cmd);
156 InsetCommandParams const & InsetInclude::params() const
164 /// the type of inclusion
173 Types type(InsetCommandParams const & params)
175 string const command_name = params.getCmdName();
177 if (command_name == "input")
179 if (command_name == "verbatiminput")
181 if (command_name == "verbatiminput*")
187 bool isVerbatim(InsetCommandParams const & params)
189 string const command_name = params.getCmdName();
190 return command_name == "verbatiminput" ||
191 command_name == "verbatiminput*";
195 string const masterFilename(Buffer const & buffer)
197 return buffer.getMasterBuffer()->fileName();
201 string const parentFilename(Buffer const & buffer)
203 return buffer.fileName();
207 string const includedFilename(Buffer const & buffer,
208 InsetCommandParams const & params)
210 return MakeAbsPath(params.getContents(),
211 OnlyPath(parentFilename(buffer)));
215 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
220 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
225 if (preview_->monitoring())
226 preview_->stopMonitoring();
228 if (type(params_) == INPUT)
229 add_preview(*preview_, *this, buffer);
233 auto_ptr<InsetBase> InsetInclude::clone() const
235 return auto_ptr<InsetBase>(new InsetInclude(*this));
239 void InsetInclude::write(Buffer const &, ostream & os) const
245 void InsetInclude::write(ostream & os) const
247 os << "Include " << params_.getCommand() << '\n'
248 << "preview " << tostr(params_.preview()) << '\n';
252 void InsetInclude::read(Buffer const &, LyXLex & lex)
258 void InsetInclude::read(LyXLex & lex)
264 string const InsetInclude::getScreenLabel(Buffer const &) const
268 switch (type(params_)) {
269 case INPUT: temp += _("Input"); break;
270 case VERB: temp += _("Verbatim Input"); break;
271 case VERBAST: temp += _("Verbatim Input*"); break;
272 case INCLUDE: temp += _("Include"); break;
277 if (params_.getContents().empty())
280 temp += OnlyFilename(params_.getContents());
288 /// return true if the file is or got loaded.
289 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
291 if (isVerbatim(params))
294 string const included_file = includedFilename(buffer, params);
295 if (!IsLyXFilename(included_file))
298 Buffer * buf = bufferlist.getBuffer(included_file);
300 // the readonly flag can/will be wrong, not anymore I think.
301 FileInfo finfo(included_file);
304 buf = bufferlist.newBuffer(included_file);
305 if (!loadLyXFile(buf, included_file))
309 buf->setParentName(parentFilename(buffer));
317 int InsetInclude::latex(Buffer const & buffer, ostream & os,
318 OutputParams const & runparams) const
320 string incfile(params_.getContents());
322 // Do nothing if no file name has been specified
326 string const included_file = includedFilename(buffer, params_);
327 Buffer const * const m_buffer = buffer.getMasterBuffer();
329 // if incfile is relative, make it relative to the master
331 if (!AbsolutePath(incfile)) {
332 incfile = MakeRelPath(included_file,
333 m_buffer->filePath());
336 // write it to a file (so far the complete file)
337 string const exportfile = ChangeExtension(incfile, ".tex");
338 string const mangled = FileName(ChangeExtension(included_file,
339 ".tex")).mangledFilename();
340 string const writefile = MakeAbsPath(mangled, m_buffer->temppath());
344 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
345 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
346 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
348 if (loadIfNeeded(buffer, params_)) {
349 Buffer * tmp = bufferlist.getBuffer(included_file);
351 if (tmp->params().textclass != m_buffer->params().textclass) {
352 string text = bformat(_("Included file `%1$s'\n"
353 "has textclass `%2$s'\n"
354 "while parent file has textclass `%3$s'."),
355 MakeDisplayPath(included_file),
356 tmp->params().getLyXTextClass().name(),
357 m_buffer->params().getLyXTextClass().name());
358 Alert::warning(_("Different textclasses"), text);
362 tmp->markDepClean(m_buffer->temppath());
365 #warning Second argument is irrelevant!
366 // since only_body is true, makeLaTeXFile will not look at second
367 // argument. Should we set it to string(), or should makeLaTeXFile
368 // make use of it somehow? (JMarc 20031002)
370 tmp->makeLaTeXFile(writefile,
371 OnlyPath(masterFilename(buffer)),
374 // Copy the file to the temp dir, so that .aux files etc.
375 // are not created in the original dir. Files included by
376 // this file will be found via input@path, see ../buffer.C.
377 unsigned long const checksum_in = sum(included_file);
378 unsigned long const checksum_out = sum(writefile);
380 if (checksum_in != checksum_out) {
381 if (!copy(included_file, writefile)) {
383 << bformat(_("Could not copy the file\n%1$s\n"
384 "into the temporary directory."),
392 if (isVerbatim(params_)) {
393 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
394 } else if (type(params_) == INPUT) {
395 runparams.exportdata->addExternalFile("latex", writefile,
398 // \input wants file with extension (default is .tex)
399 if (!IsLyXFilename(included_file)) {
400 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
402 os << '\\' << params_.getCmdName() << '{'
403 << ChangeExtension(incfile, ".tex")
407 runparams.exportdata->addExternalFile("latex", writefile,
410 // \include don't want extension and demands that the
411 // file really have .tex
412 os << '\\' << params_.getCmdName() << '{'
413 << ChangeExtension(incfile, string())
421 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
422 OutputParams const &) const
424 if (isVerbatim(params_))
425 os << GetFileContents(includedFilename(buffer, params_));
430 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
431 OutputParams const & runparams) const
433 string incfile(params_.getContents());
435 // Do nothing if no file name has been specified
439 string const included_file = includedFilename(buffer, params_);
441 // write it to a file (so far the complete file)
442 string const exportfile = ChangeExtension(incfile, ".sgml");
443 string writefile = ChangeExtension(included_file, ".sgml");
445 if (loadIfNeeded(buffer, params_)) {
446 Buffer * tmp = bufferlist.getBuffer(included_file);
448 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
449 buffer.getMasterBuffer()->temppath());
453 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
454 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
455 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
457 tmp->makeLinuxDocFile(writefile, runparams, true);
460 if (isVerbatim(params_)) {
462 << GetFileContents(included_file)
465 runparams.exportdata->addExternalFile("linuxdoc", writefile,
467 os << '&' << include_label << ';';
474 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
475 OutputParams const & runparams) const
477 string incfile(params_.getContents());
479 // Do nothing if no file name has been specified
483 string const included_file = includedFilename(buffer, params_);
485 // write it to a file (so far the complete file)
486 string const exportfile = ChangeExtension(incfile, ".sgml");
487 string writefile = ChangeExtension(included_file, ".sgml");
489 if (loadIfNeeded(buffer, params_)) {
490 Buffer * tmp = bufferlist.getBuffer(included_file);
492 string const mangled = FileName(writefile).mangledFilename();
493 writefile = MakeAbsPath(mangled,
494 buffer.getMasterBuffer()->temppath());
498 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
499 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
500 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
502 tmp->makeDocBookFile(writefile, runparams, true);
505 runparams.exportdata->addExternalFile("docbook", writefile,
507 runparams.exportdata->addExternalFile("docbook-xml", writefile,
510 if (isVerbatim(params_)) {
511 os << "<inlinegraphic fileref=\""
512 << '&' << include_label << ';'
513 << "\" format=\"linespecific\">";
515 os << '&' << include_label << ';';
521 void InsetInclude::validate(LaTeXFeatures & features) const
523 string incfile(params_.getContents());
526 Buffer const & buffer = features.buffer();
528 string const included_file = includedFilename(buffer, params_);
530 if (IsLyXFilename(included_file))
531 writefile = ChangeExtension(included_file, ".sgml");
533 writefile = included_file;
535 if (!features.nice() && !isVerbatim(params_)) {
536 incfile = FileName(writefile).mangledFilename();
537 writefile = MakeAbsPath(incfile,
538 buffer.getMasterBuffer()->temppath());
541 features.includeFile(include_label, writefile);
543 if (isVerbatim(params_))
544 features.require("verbatim");
546 // Here we must do the fun stuff...
547 // Load the file in the include if it needs
549 if (loadIfNeeded(buffer, params_)) {
551 Buffer * const tmp = bufferlist.getBuffer(included_file);
553 // We must temporarily change features.buffer,
554 // otherwise it would always be the master buffer,
555 // and nested includes would not work.
556 features.setBuffer(*tmp);
557 tmp->validate(features);
558 features.setBuffer(buffer);
564 void InsetInclude::getLabelList(Buffer const & buffer,
565 std::vector<string> & list) const
567 if (loadIfNeeded(buffer, params_)) {
568 string const included_file = includedFilename(buffer, params_);
569 Buffer * tmp = bufferlist.getBuffer(included_file);
570 tmp->setParentName("");
571 tmp->getLabelList(list);
572 tmp->setParentName(parentFilename(buffer));
577 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
578 std::vector<std::pair<string,string> > & keys) const
580 if (loadIfNeeded(buffer, params_)) {
581 string const included_file = includedFilename(buffer, params_);
582 Buffer * tmp = bufferlist.getBuffer(included_file);
583 tmp->setParentName("");
584 tmp->fillWithBibKeys(keys);
585 tmp->setParentName(parentFilename(buffer));
590 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
592 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
594 bool use_preview = false;
595 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
596 lyx::graphics::PreviewImage const * pimage =
597 preview_->getPreviewImage(*mi.base.bv->buffer());
598 use_preview = pimage && pimage->image();
602 preview_->metrics(mi, dim);
606 button_.update(getScreenLabel(*mi.base.bv->buffer()),
607 editable() != NOT_EDITABLE);
609 button_.metrics(mi, dim);
611 int center_indent = type(params_) == INPUT ?
612 0 : (mi.base.textwidth - dim.wid) / 2;
613 Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
616 dim.wid = mi.base.textwidth;
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 + button_.box().x1, y);
637 button_.draw(pi, x + button_.box().x1, y);
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";