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 || runparams.dryrun)
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 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
411 "latex" : "pdflatex";
412 if (isVerbatim(params_)) {
413 incfile = latex_path(incfile);
414 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
415 } else if (type(params_) == INPUT) {
416 runparams.exportdata->addExternalFile(tex_format, writefile,
419 // \input wants file with extension (default is .tex)
420 if (!isLyXFilename(included_file)) {
421 incfile = latex_path(incfile);
422 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
424 incfile = changeExtension(incfile, ".tex");
425 incfile = latex_path(incfile);
426 os << '\\' << params_.getCmdName() << '{'
431 runparams.exportdata->addExternalFile(tex_format, writefile,
434 // \include don't want extension and demands that the
435 // file really have .tex
436 incfile = changeExtension(incfile, string());
437 incfile = latex_path(incfile);
438 os << '\\' << params_.getCmdName() << '{'
447 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
448 OutputParams const &) const
450 if (isVerbatim(params_))
451 os << getFileContents(includedFilename(buffer, params_));
456 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
457 OutputParams const & runparams) const
459 string incfile(params_.getContents());
461 // Do nothing if no file name has been specified
465 string const included_file = includedFilename(buffer, params_);
467 // write it to a file (so far the complete file)
468 string const exportfile = changeExtension(incfile, ".sgml");
469 string writefile = changeExtension(included_file, ".sgml");
471 if (loadIfNeeded(buffer, params_)) {
472 Buffer * tmp = bufferlist.getBuffer(included_file);
474 writefile = makeAbsPath(FileName(writefile).mangledFilename(),
475 buffer.getMasterBuffer()->temppath());
479 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
480 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
481 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
483 tmp->makeLinuxDocFile(writefile, runparams, true);
486 if (isVerbatim(params_)) {
488 << getFileContents(included_file)
491 runparams.exportdata->addExternalFile("linuxdoc", writefile,
493 os << '&' << include_label << ';';
500 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
501 OutputParams const & runparams) const
503 string incfile(params_.getContents());
505 // Do nothing if no file name has been specified
509 string const included_file = includedFilename(buffer, params_);
511 // write it to a file (so far the complete file)
512 string const exportfile = changeExtension(incfile, ".sgml");
513 string writefile = changeExtension(included_file, ".sgml");
515 if (loadIfNeeded(buffer, params_)) {
516 Buffer * tmp = bufferlist.getBuffer(included_file);
518 string const mangled = FileName(writefile).mangledFilename();
519 writefile = makeAbsPath(mangled,
520 buffer.getMasterBuffer()->temppath());
524 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
525 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
526 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
528 tmp->makeDocBookFile(writefile, runparams, true);
531 runparams.exportdata->addExternalFile("docbook", writefile,
533 runparams.exportdata->addExternalFile("docbook-xml", writefile,
536 if (isVerbatim(params_)) {
537 os << "<inlinegraphic fileref=\""
538 << '&' << include_label << ';'
539 << "\" format=\"linespecific\">";
541 os << '&' << include_label << ';';
547 void InsetInclude::validate(LaTeXFeatures & features) const
549 string incfile(params_.getContents());
552 Buffer const & buffer = features.buffer();
554 string const included_file = includedFilename(buffer, params_);
556 if (isLyXFilename(included_file))
557 writefile = changeExtension(included_file, ".sgml");
559 writefile = included_file;
561 if (!features.runparams().nice && !isVerbatim(params_)) {
562 incfile = FileName(writefile).mangledFilename();
563 writefile = makeAbsPath(incfile,
564 buffer.getMasterBuffer()->temppath());
567 features.includeFile(include_label, writefile);
569 if (isVerbatim(params_))
570 features.require("verbatim");
572 // Here we must do the fun stuff...
573 // Load the file in the include if it needs
575 if (loadIfNeeded(buffer, params_)) {
577 Buffer * const tmp = bufferlist.getBuffer(included_file);
579 // We must temporarily change features.buffer,
580 // otherwise it would always be the master buffer,
581 // and nested includes would not work.
582 features.setBuffer(*tmp);
583 tmp->validate(features);
584 features.setBuffer(buffer);
590 void InsetInclude::getLabelList(Buffer const & buffer,
591 std::vector<string> & list) const
593 if (loadIfNeeded(buffer, params_)) {
594 string const included_file = includedFilename(buffer, params_);
595 Buffer * tmp = bufferlist.getBuffer(included_file);
596 tmp->setParentName("");
597 tmp->getLabelList(list);
598 tmp->setParentName(parentFilename(buffer));
603 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
604 std::vector<std::pair<string,string> > & keys) const
606 if (loadIfNeeded(buffer, params_)) {
607 string const included_file = includedFilename(buffer, params_);
608 Buffer * tmp = bufferlist.getBuffer(included_file);
609 tmp->setParentName("");
610 tmp->fillWithBibKeys(keys);
611 tmp->setParentName(parentFilename(buffer));
616 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
618 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
620 bool use_preview = false;
621 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
622 lyx::graphics::PreviewImage const * pimage =
623 preview_->getPreviewImage(*mi.base.bv->buffer());
624 use_preview = pimage && pimage->image();
628 preview_->metrics(mi, dim);
632 button_.update(getScreenLabel(*mi.base.bv->buffer()),
635 button_.metrics(mi, dim);
638 Box b(0, dim.wid, -dim.asc, dim.des);
645 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
647 setPosCache(pi, x, y);
649 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
651 bool use_preview = false;
652 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
653 lyx::graphics::PreviewImage const * pimage =
654 preview_->getPreviewImage(*pi.base.bv->buffer());
655 use_preview = pimage && pimage->image();
659 preview_->draw(pi, x, y);
661 button_.draw(pi, x, y);
664 bool InsetInclude::display() const
666 return type(params_) != INPUT;
675 void InsetInclude::fileChanged() const
677 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
681 Buffer const & buffer = *buffer_ptr;
682 preview_->removePreview(buffer);
683 add_preview(*preview_.get(), *this, buffer);
684 preview_->startLoading(buffer);
690 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
692 string const included_file = includedFilename(buffer, params);
694 return type(params) == INPUT && params.preview() &&
695 isFileReadable(included_file);
699 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
702 OutputParams runparams;
703 runparams.flavor = OutputParams::LATEX;
704 inset.latex(buffer, os, runparams);
710 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
711 Buffer const & buffer)
713 InsetCommandParams const & params = inset.params();
714 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
715 preview_wanted(params, buffer)) {
716 renderer.setAbsFile(includedFilename(buffer, params));
717 string const snippet = latex_string(inset, buffer);
718 renderer.addPreview(snippet, buffer);
725 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
727 Buffer const & buffer = ploader.buffer();
728 if (preview_wanted(params(), buffer)) {
729 preview_->setAbsFile(includedFilename(buffer, params()));
730 string const snippet = latex_string(*this, buffer);
731 preview_->addPreview(snippet, ploader);
736 string const InsetIncludeMailer::name_("include");
738 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
743 string const InsetIncludeMailer::inset2string(Buffer const &) const
745 return params2string(inset_.params());
749 void InsetIncludeMailer::string2params(string const & in,
750 InsetCommandParams & params)
752 params = InsetCommandParams();
756 istringstream data(in);
762 if (!lex || name != name_)
763 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
765 // This is part of the inset proper that is usually swallowed
766 // by LyXText::readInset
769 if (!lex || id != "Include")
770 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
772 InsetInclude inset(params);
774 params = inset.params();
779 InsetIncludeMailer::params2string(InsetCommandParams const & params)
781 InsetInclude inset(params);
783 data << name_ << ' ';
785 data << "\\end_inset\n";