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/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/lyxalgo.h"
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"
57 using lyx::odocstream;
58 using lyx::support::addName;
59 using lyx::support::absolutePath;
60 using lyx::support::bformat;
61 using lyx::support::changeExtension;
62 using lyx::support::contains;
63 using lyx::support::copy;
64 using lyx::support::FileName;
65 using lyx::support::getFileContents;
66 using lyx::support::isFileReadable;
67 using lyx::support::isLyXFilename;
68 using lyx::support::latex_path;
69 using lyx::support::makeAbsPath;
70 using lyx::support::makeDisplayPath;
71 using lyx::support::makeRelPath;
72 using lyx::support::onlyFilename;
73 using lyx::support::onlyPath;
74 using lyx::support::subst;
75 using lyx::support::sum;
80 using std::istringstream;
82 using std::ostringstream;
84 namespace Alert = lyx::frontend::Alert;
85 namespace fs = boost::filesystem;
90 string const uniqueID()
92 static unsigned int seed = 1000;
93 return "file" + convert<string>(++seed);
99 InsetInclude::InsetInclude(InsetCommandParams const & p)
100 : params_(p), include_label(uniqueID()),
101 preview_(new RenderMonitoredPreview(this)),
104 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
108 InsetInclude::InsetInclude(InsetInclude const & other)
110 params_(other.params_),
111 include_label(other.include_label),
112 preview_(new RenderMonitoredPreview(this)),
115 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
119 InsetInclude::~InsetInclude()
121 InsetIncludeMailer(*this).hideDialog();
125 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
127 switch (cmd.action) {
129 case LFUN_INSET_MODIFY: {
130 InsetCommandParams p("include");
131 InsetIncludeMailer::string2params(lyx::to_utf8(cmd.argument()), p);
132 if (!p.getCmdName().empty()) {
133 set(p, cur.buffer());
134 cur.buffer().updateBibfilesCache();
140 case LFUN_INSET_DIALOG_UPDATE:
141 InsetIncludeMailer(*this).updateDialog(&cur.bv());
144 case LFUN_MOUSE_RELEASE:
145 InsetIncludeMailer(*this).showDialog(&cur.bv());
149 InsetBase::doDispatch(cur, cmd);
155 bool InsetInclude::getStatus(LCursor & cur, FuncRequest const & cmd,
156 FuncStatus & flag) const
158 switch (cmd.action) {
160 case LFUN_INSET_MODIFY:
161 case LFUN_INSET_DIALOG_UPDATE:
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 " << lyx::to_utf8(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 docstring const InsetInclude::getScreenLabel(Buffer const &) const
283 switch (type(params_)) {
288 temp += _("Verbatim Input");
291 temp += _("Verbatim Input*");
294 temp += _("Include");
300 if (params_.getContents().empty())
303 // FIXME: We don't know the encoding of the filename
304 temp += lyx::from_ascii(onlyFilename(params_.getContents()));
312 /// return the child buffer if the file is a LyX doc and is loaded
313 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
315 if (isVerbatim(params))
318 string const included_file = includedFilename(buffer, params);
319 if (!isLyXFilename(included_file))
322 return theBufferList().getBuffer(included_file);
326 /// return true if the file is or got loaded.
327 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
329 if (isVerbatim(params))
332 string const included_file = includedFilename(buffer, params);
333 if (!isLyXFilename(included_file))
336 Buffer * buf = theBufferList().getBuffer(included_file);
338 // the readonly flag can/will be wrong, not anymore I think.
339 if (!fs::exists(included_file))
341 buf = theBufferList().newBuffer(included_file);
342 if (!loadLyXFile(buf, included_file))
346 buf->setParentName(parentFilename(buffer));
354 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
355 OutputParams const & runparams) const
357 string incfile(params_.getContents());
359 // Do nothing if no file name has been specified
363 string const included_file = includedFilename(buffer, params_);
364 Buffer const * const m_buffer = buffer.getMasterBuffer();
366 // if incfile is relative, make it relative to the master
368 if (!absolutePath(incfile)) {
369 incfile = makeRelPath(included_file,
370 m_buffer->filePath());
373 // write it to a file (so far the complete file)
374 string const exportfile = changeExtension(incfile, ".tex");
375 string const mangled = FileName(changeExtension(included_file,
376 ".tex")).mangledFilename();
377 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
381 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
382 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
383 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
385 if (runparams.inComment || runparams.dryrun)
386 // Don't try to load or copy the file
388 else if (loadIfNeeded(buffer, params_)) {
389 Buffer * tmp = theBufferList().getBuffer(included_file);
391 if (tmp->params().textclass != m_buffer->params().textclass) {
393 docstring text = bformat(_("Included file `%1$s'\n"
394 "has textclass `%2$s'\n"
395 "while parent file has textclass `%3$s'."),
396 makeDisplayPath(included_file),
397 lyx::from_utf8(tmp->params().getLyXTextClass().name()),
398 lyx::from_utf8(m_buffer->params().getLyXTextClass().name()));
399 Alert::warning(_("Different textclasses"), text);
403 tmp->markDepClean(m_buffer->temppath());
406 #warning handle non existing files
407 #warning Second argument is irrelevant!
408 // since only_body is true, makeLaTeXFile will not look at second
409 // argument. Should we set it to string(), or should makeLaTeXFile
410 // make use of it somehow? (JMarc 20031002)
412 tmp->makeLaTeXFile(writefile,
413 onlyPath(masterFilename(buffer)),
416 // Copy the file to the temp dir, so that .aux files etc.
417 // are not created in the original dir. Files included by
418 // this file will be found via input@path, see ../buffer.C.
419 unsigned long const checksum_in = sum(included_file);
420 unsigned long const checksum_out = sum(writefile);
422 if (checksum_in != checksum_out) {
423 if (!copy(included_file, writefile)) {
426 << lyx::to_utf8(bformat(_("Could not copy the file\n%1$s\n"
427 "into the temporary directory."),
428 lyx::from_utf8(included_file)))
435 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
436 "latex" : "pdflatex";
437 if (isVerbatim(params_)) {
438 incfile = latex_path(incfile);
440 os << '\\' << lyx::from_ascii(params_.getCmdName()) << '{'
441 << lyx::from_utf8(incfile) << '}';
442 } else if (type(params_) == INPUT) {
443 runparams.exportdata->addExternalFile(tex_format, writefile,
446 // \input wants file with extension (default is .tex)
447 if (!isLyXFilename(included_file)) {
448 incfile = latex_path(incfile);
450 os << '\\' << lyx::from_ascii(params_.getCmdName())
451 << '{' << lyx::from_utf8(incfile) << '}';
453 incfile = changeExtension(incfile, ".tex");
454 incfile = latex_path(incfile);
456 os << '\\' << lyx::from_ascii(params_.getCmdName())
457 << '{' << lyx::from_utf8(incfile) << '}';
460 runparams.exportdata->addExternalFile(tex_format, writefile,
463 // \include don't want extension and demands that the
464 // file really have .tex
465 incfile = changeExtension(incfile, string());
466 incfile = latex_path(incfile);
468 os << '\\' << lyx::from_ascii(params_.getCmdName()) << '{'
469 << lyx::from_utf8(incfile) << '}';
476 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
477 OutputParams const &) const
479 if (isVerbatim(params_)) {
480 // FIXME: We don't know the encoding of the file
481 docstring const str = lyx::from_utf8(
482 getFileContents(includedFilename(buffer, params_)));
484 // Return how many newlines we issued.
485 return int(lyx::count(str.begin(), str.end(), '\n'));
491 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
492 OutputParams const & runparams) const
494 string incfile(params_.getContents());
496 // Do nothing if no file name has been specified
500 string const included_file = includedFilename(buffer, params_);
502 // write it to a file (so far the complete file)
503 string const exportfile = changeExtension(incfile, ".sgml");
504 string writefile = changeExtension(included_file, ".sgml");
506 if (loadIfNeeded(buffer, params_)) {
507 Buffer * tmp = theBufferList().getBuffer(included_file);
509 string const mangled = FileName(writefile).mangledFilename();
510 writefile = makeAbsPath(mangled,
511 buffer.getMasterBuffer()->temppath());
515 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
516 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
517 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
519 tmp->makeDocBookFile(writefile, runparams, true);
522 runparams.exportdata->addExternalFile("docbook", writefile,
524 runparams.exportdata->addExternalFile("docbook-xml", writefile,
527 if (isVerbatim(params_)) {
528 os << "<inlinegraphic fileref=\""
529 << '&' << include_label << ';'
530 << "\" format=\"linespecific\">";
532 os << '&' << include_label << ';';
538 void InsetInclude::validate(LaTeXFeatures & features) const
540 string incfile(params_.getContents());
543 Buffer const & buffer = features.buffer();
545 string const included_file = includedFilename(buffer, params_);
547 if (isLyXFilename(included_file))
548 writefile = changeExtension(included_file, ".sgml");
550 writefile = included_file;
552 if (!features.runparams().nice && !isVerbatim(params_)) {
553 incfile = FileName(writefile).mangledFilename();
554 writefile = makeAbsPath(incfile,
555 buffer.getMasterBuffer()->temppath());
558 features.includeFile(include_label, writefile);
560 if (isVerbatim(params_))
561 features.require("verbatim");
563 // Here we must do the fun stuff...
564 // Load the file in the include if it needs
566 if (loadIfNeeded(buffer, params_)) {
568 Buffer * const tmp = theBufferList().getBuffer(included_file);
570 // We must temporarily change features.buffer,
571 // otherwise it would always be the master buffer,
572 // and nested includes would not work.
573 features.setBuffer(*tmp);
574 tmp->validate(features);
575 features.setBuffer(buffer);
581 void InsetInclude::getLabelList(Buffer const & buffer,
582 std::vector<docstring> & list) const
584 if (loadIfNeeded(buffer, params_)) {
585 string const included_file = includedFilename(buffer, params_);
586 Buffer * tmp = theBufferList().getBuffer(included_file);
587 tmp->setParentName("");
588 tmp->getLabelList(list);
589 tmp->setParentName(parentFilename(buffer));
594 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
595 std::vector<std::pair<string,string> > & keys) const
597 if (loadIfNeeded(buffer, params_)) {
598 string const included_file = includedFilename(buffer, params_);
599 Buffer * tmp = theBufferList().getBuffer(included_file);
600 tmp->setParentName("");
601 tmp->fillWithBibKeys(keys);
602 tmp->setParentName(parentFilename(buffer));
607 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
609 Buffer * const tmp = getChildBuffer(buffer, params_);
611 tmp->setParentName("");
612 tmp->updateBibfilesCache();
613 tmp->setParentName(parentFilename(buffer));
618 std::vector<string> const &
619 InsetInclude::getBibfilesCache(Buffer const & buffer) const
621 Buffer * const tmp = getChildBuffer(buffer, params_);
623 tmp->setParentName("");
624 std::vector<string> const & cache = tmp->getBibfilesCache();
625 tmp->setParentName(parentFilename(buffer));
628 static std::vector<string> const empty;
633 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
635 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
637 bool use_preview = false;
638 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
639 lyx::graphics::PreviewImage const * pimage =
640 preview_->getPreviewImage(*mi.base.bv->buffer());
641 use_preview = pimage && pimage->image();
645 preview_->metrics(mi, dim);
649 button_.update(getScreenLabel(*mi.base.bv->buffer()),
652 button_.metrics(mi, dim);
655 Box b(0, dim.wid, -dim.asc, dim.des);
662 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
664 setPosCache(pi, x, y);
666 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
668 bool use_preview = false;
669 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
670 lyx::graphics::PreviewImage const * pimage =
671 preview_->getPreviewImage(*pi.base.bv->buffer());
672 use_preview = pimage && pimage->image();
676 preview_->draw(pi, x, y);
678 button_.draw(pi, x, y);
681 bool InsetInclude::display() const
683 return type(params_) != INPUT;
692 void InsetInclude::fileChanged() const
694 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
698 Buffer const & buffer = *buffer_ptr;
699 preview_->removePreview(buffer);
700 add_preview(*preview_.get(), *this, buffer);
701 preview_->startLoading(buffer);
707 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
709 string const included_file = includedFilename(buffer, params);
711 return type(params) == INPUT && params.preview() &&
712 isFileReadable(included_file);
716 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
718 lyx::odocstringstream os;
719 OutputParams runparams;
720 runparams.flavor = OutputParams::LATEX;
721 inset.latex(buffer, os, runparams);
727 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
728 Buffer const & buffer)
730 InsetCommandParams const & params = inset.params();
731 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
732 preview_wanted(params, buffer)) {
733 renderer.setAbsFile(includedFilename(buffer, params));
734 docstring const snippet = latex_string(inset, buffer);
735 renderer.addPreview(snippet, buffer);
742 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
744 Buffer const & buffer = ploader.buffer();
745 if (preview_wanted(params(), buffer)) {
746 preview_->setAbsFile(includedFilename(buffer, params()));
747 docstring const snippet = latex_string(*this, buffer);
748 preview_->addPreview(snippet, ploader);
753 string const InsetIncludeMailer::name_("include");
755 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
760 string const InsetIncludeMailer::inset2string(Buffer const &) const
762 return params2string(inset_.params());
766 void InsetIncludeMailer::string2params(string const & in,
767 InsetCommandParams & params)
773 istringstream data(in);
779 if (!lex || name != name_)
780 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
782 // This is part of the inset proper that is usually swallowed
783 // by LyXText::readInset
786 if (!lex || id != "Include")
787 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
789 InsetInclude inset(params);
791 params = inset.params();
796 InsetIncludeMailer::params2string(InsetCommandParams const & params)
798 InsetInclude inset(params);
800 data << name_ << ' ';
802 data << "\\end_inset\n";