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::support::addName;
58 using lyx::support::absolutePath;
59 using lyx::support::bformat;
60 using lyx::support::changeExtension;
61 using lyx::support::contains;
62 using lyx::support::copy;
63 using lyx::support::FileName;
64 using lyx::support::getFileContents;
65 using lyx::support::isFileReadable;
66 using lyx::support::isLyXFilename;
67 using lyx::support::latex_path;
68 using lyx::support::makeAbsPath;
69 using lyx::support::makeDisplayPath;
70 using lyx::support::makeRelPath;
71 using lyx::support::onlyFilename;
72 using lyx::support::onlyPath;
73 using lyx::support::subst;
74 using lyx::support::sum;
79 using std::istringstream;
81 using std::ostringstream;
83 namespace Alert = lyx::frontend::Alert;
84 namespace fs = boost::filesystem;
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(lyx::to_utf8(cmd.argument()), p);
131 if (!p.getCmdName().empty()) {
132 set(p, cur.buffer());
133 cur.buffer().updateBibfilesCache();
139 case LFUN_INSET_DIALOG_UPDATE:
140 InsetIncludeMailer(*this).updateDialog(&cur.bv());
143 case LFUN_MOUSE_RELEASE:
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:
165 return InsetBase::getStatus(cur, cmd, flag);
170 InsetCommandParams const & InsetInclude::params() const
178 /// the type of inclusion
187 Types type(InsetCommandParams const & params)
189 string const command_name = params.getCmdName();
191 if (command_name == "input")
193 if (command_name == "verbatiminput")
195 if (command_name == "verbatiminput*")
201 bool isVerbatim(InsetCommandParams const & params)
203 string const command_name = params.getCmdName();
204 return command_name == "verbatiminput" ||
205 command_name == "verbatiminput*";
209 string const masterFilename(Buffer const & buffer)
211 return buffer.getMasterBuffer()->fileName();
215 string const parentFilename(Buffer const & buffer)
217 return buffer.fileName();
221 string const includedFilename(Buffer const & buffer,
222 InsetCommandParams const & params)
224 return makeAbsPath(params.getContents(),
225 onlyPath(parentFilename(buffer)));
229 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
234 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
239 if (preview_->monitoring())
240 preview_->stopMonitoring();
242 if (type(params_) == INPUT)
243 add_preview(*preview_, *this, buffer);
247 auto_ptr<InsetBase> InsetInclude::doClone() const
249 return auto_ptr<InsetBase>(new InsetInclude(*this));
253 void InsetInclude::write(Buffer const &, ostream & os) const
259 void InsetInclude::write(ostream & os) const
261 os << "Include " << params_.getCommand() << '\n'
262 << "preview " << convert<string>(params_.preview()) << '\n';
266 void InsetInclude::read(Buffer const &, LyXLex & lex)
272 void InsetInclude::read(LyXLex & lex)
278 docstring const InsetInclude::getScreenLabel(Buffer const &) const
282 switch (type(params_)) {
287 temp += _("Verbatim Input");
290 temp += _("Verbatim Input*");
293 temp += _("Include");
299 if (params_.getContents().empty())
302 // FIXME: We don't know the encoding of the filename
303 temp += lyx::from_ascii(onlyFilename(params_.getContents()));
311 /// return the child buffer if the file is a LyX doc and is loaded
312 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
314 if (isVerbatim(params))
317 string const included_file = includedFilename(buffer, params);
318 if (!isLyXFilename(included_file))
321 return theBufferList().getBuffer(included_file);
325 /// return true if the file is or got loaded.
326 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
328 if (isVerbatim(params))
331 string const included_file = includedFilename(buffer, params);
332 if (!isLyXFilename(included_file))
335 Buffer * buf = theBufferList().getBuffer(included_file);
337 // the readonly flag can/will be wrong, not anymore I think.
338 if (!fs::exists(included_file))
340 buf = theBufferList().newBuffer(included_file);
341 if (!loadLyXFile(buf, included_file))
345 buf->setParentName(parentFilename(buffer));
353 int InsetInclude::latex(Buffer const & buffer, ostream & os,
354 OutputParams const & runparams) const
356 string incfile(params_.getContents());
358 // Do nothing if no file name has been specified
362 string const included_file = includedFilename(buffer, params_);
363 Buffer const * const m_buffer = buffer.getMasterBuffer();
365 // if incfile is relative, make it relative to the master
367 if (!absolutePath(incfile)) {
368 incfile = makeRelPath(included_file,
369 m_buffer->filePath());
372 // write it to a file (so far the complete file)
373 string const exportfile = changeExtension(incfile, ".tex");
374 string const mangled = FileName(changeExtension(included_file,
375 ".tex")).mangledFilename();
376 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
380 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
381 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
382 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
384 if (runparams.inComment || runparams.dryrun)
385 // Don't try to load or copy the file
387 else if (loadIfNeeded(buffer, params_)) {
388 Buffer * tmp = theBufferList().getBuffer(included_file);
390 if (tmp->params().textclass != m_buffer->params().textclass) {
392 docstring text = bformat(_("Included file `%1$s'\n"
393 "has textclass `%2$s'\n"
394 "while parent file has textclass `%3$s'."),
395 makeDisplayPath(included_file),
396 lyx::from_utf8(tmp->params().getLyXTextClass().name()),
397 lyx::from_utf8(m_buffer->params().getLyXTextClass().name()));
398 Alert::warning(_("Different textclasses"), text);
402 tmp->markDepClean(m_buffer->temppath());
405 #warning handle non existing files
406 #warning Second argument is irrelevant!
407 // since only_body is true, makeLaTeXFile will not look at second
408 // argument. Should we set it to string(), or should makeLaTeXFile
409 // make use of it somehow? (JMarc 20031002)
411 tmp->makeLaTeXFile(writefile,
412 onlyPath(masterFilename(buffer)),
415 // Copy the file to the temp dir, so that .aux files etc.
416 // are not created in the original dir. Files included by
417 // this file will be found via input@path, see ../buffer.C.
418 unsigned long const checksum_in = sum(included_file);
419 unsigned long const checksum_out = sum(writefile);
421 if (checksum_in != checksum_out) {
422 if (!copy(included_file, writefile)) {
425 << lyx::to_utf8(bformat(_("Could not copy the file\n%1$s\n"
426 "into the temporary directory."),
427 lyx::from_utf8(included_file)))
434 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
435 "latex" : "pdflatex";
436 if (isVerbatim(params_)) {
437 incfile = latex_path(incfile);
438 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
439 } else if (type(params_) == INPUT) {
440 runparams.exportdata->addExternalFile(tex_format, writefile,
443 // \input wants file with extension (default is .tex)
444 if (!isLyXFilename(included_file)) {
445 incfile = latex_path(incfile);
446 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
448 incfile = changeExtension(incfile, ".tex");
449 incfile = latex_path(incfile);
450 os << '\\' << params_.getCmdName() << '{'
455 runparams.exportdata->addExternalFile(tex_format, writefile,
458 // \include don't want extension and demands that the
459 // file really have .tex
460 incfile = changeExtension(incfile, string());
461 incfile = latex_path(incfile);
462 os << '\\' << params_.getCmdName() << '{'
471 int InsetInclude::plaintext(Buffer const & buffer, lyx::odocstream & os,
472 OutputParams const &) const
474 if (isVerbatim(params_)) {
475 // FIXME: We don't know the encoding of the file
476 docstring const str = lyx::from_utf8(
477 getFileContents(includedFilename(buffer, params_)));
479 // Return how many newlines we issued.
480 return int(lyx::count(str.begin(), str.end(), '\n'));
486 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
487 OutputParams const & runparams) const
489 string incfile(params_.getContents());
491 // Do nothing if no file name has been specified
495 string const included_file = includedFilename(buffer, params_);
497 // write it to a file (so far the complete file)
498 string const exportfile = changeExtension(incfile, ".sgml");
499 string writefile = changeExtension(included_file, ".sgml");
501 if (loadIfNeeded(buffer, params_)) {
502 Buffer * tmp = theBufferList().getBuffer(included_file);
504 string const mangled = FileName(writefile).mangledFilename();
505 writefile = makeAbsPath(mangled,
506 buffer.getMasterBuffer()->temppath());
510 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
511 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
512 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
514 tmp->makeDocBookFile(writefile, runparams, true);
517 runparams.exportdata->addExternalFile("docbook", writefile,
519 runparams.exportdata->addExternalFile("docbook-xml", writefile,
522 if (isVerbatim(params_)) {
523 os << "<inlinegraphic fileref=\""
524 << '&' << include_label << ';'
525 << "\" format=\"linespecific\">";
527 os << '&' << include_label << ';';
533 void InsetInclude::validate(LaTeXFeatures & features) const
535 string incfile(params_.getContents());
538 Buffer const & buffer = features.buffer();
540 string const included_file = includedFilename(buffer, params_);
542 if (isLyXFilename(included_file))
543 writefile = changeExtension(included_file, ".sgml");
545 writefile = included_file;
547 if (!features.runparams().nice && !isVerbatim(params_)) {
548 incfile = FileName(writefile).mangledFilename();
549 writefile = makeAbsPath(incfile,
550 buffer.getMasterBuffer()->temppath());
553 features.includeFile(include_label, writefile);
555 if (isVerbatim(params_))
556 features.require("verbatim");
558 // Here we must do the fun stuff...
559 // Load the file in the include if it needs
561 if (loadIfNeeded(buffer, params_)) {
563 Buffer * const tmp = theBufferList().getBuffer(included_file);
565 // We must temporarily change features.buffer,
566 // otherwise it would always be the master buffer,
567 // and nested includes would not work.
568 features.setBuffer(*tmp);
569 tmp->validate(features);
570 features.setBuffer(buffer);
576 void InsetInclude::getLabelList(Buffer const & buffer,
577 std::vector<docstring> & list) const
579 if (loadIfNeeded(buffer, params_)) {
580 string const included_file = includedFilename(buffer, params_);
581 Buffer * tmp = theBufferList().getBuffer(included_file);
582 tmp->setParentName("");
583 tmp->getLabelList(list);
584 tmp->setParentName(parentFilename(buffer));
589 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
590 std::vector<std::pair<string,string> > & keys) const
592 if (loadIfNeeded(buffer, params_)) {
593 string const included_file = includedFilename(buffer, params_);
594 Buffer * tmp = theBufferList().getBuffer(included_file);
595 tmp->setParentName("");
596 tmp->fillWithBibKeys(keys);
597 tmp->setParentName(parentFilename(buffer));
602 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
604 Buffer * const tmp = getChildBuffer(buffer, params_);
606 tmp->setParentName("");
607 tmp->updateBibfilesCache();
608 tmp->setParentName(parentFilename(buffer));
613 std::vector<string> const &
614 InsetInclude::getBibfilesCache(Buffer const & buffer) const
616 Buffer * const tmp = getChildBuffer(buffer, params_);
618 tmp->setParentName("");
619 std::vector<string> const & cache = tmp->getBibfilesCache();
620 tmp->setParentName(parentFilename(buffer));
623 static std::vector<string> const empty;
628 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
630 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
632 bool use_preview = false;
633 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
634 lyx::graphics::PreviewImage const * pimage =
635 preview_->getPreviewImage(*mi.base.bv->buffer());
636 use_preview = pimage && pimage->image();
640 preview_->metrics(mi, dim);
644 button_.update(getScreenLabel(*mi.base.bv->buffer()),
647 button_.metrics(mi, dim);
650 Box b(0, dim.wid, -dim.asc, dim.des);
657 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
659 setPosCache(pi, x, y);
661 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
663 bool use_preview = false;
664 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
665 lyx::graphics::PreviewImage const * pimage =
666 preview_->getPreviewImage(*pi.base.bv->buffer());
667 use_preview = pimage && pimage->image();
671 preview_->draw(pi, x, y);
673 button_.draw(pi, x, y);
676 bool InsetInclude::display() const
678 return type(params_) != INPUT;
687 void InsetInclude::fileChanged() const
689 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
693 Buffer const & buffer = *buffer_ptr;
694 preview_->removePreview(buffer);
695 add_preview(*preview_.get(), *this, buffer);
696 preview_->startLoading(buffer);
702 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
704 string const included_file = includedFilename(buffer, params);
706 return type(params) == INPUT && params.preview() &&
707 isFileReadable(included_file);
711 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
714 OutputParams runparams;
715 runparams.flavor = OutputParams::LATEX;
716 inset.latex(buffer, os, runparams);
722 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
723 Buffer const & buffer)
725 InsetCommandParams const & params = inset.params();
726 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
727 preview_wanted(params, buffer)) {
728 renderer.setAbsFile(includedFilename(buffer, params));
729 string const snippet = latex_string(inset, buffer);
730 renderer.addPreview(snippet, buffer);
737 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
739 Buffer const & buffer = ploader.buffer();
740 if (preview_wanted(params(), buffer)) {
741 preview_->setAbsFile(includedFilename(buffer, params()));
742 string const snippet = latex_string(*this, buffer);
743 preview_->addPreview(snippet, ploader);
748 string const InsetIncludeMailer::name_("include");
750 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
755 string const InsetIncludeMailer::inset2string(Buffer const &) const
757 return params2string(inset_.params());
761 void InsetIncludeMailer::string2params(string const & in,
762 InsetCommandParams & params)
764 params = InsetCommandParams();
768 istringstream data(in);
774 if (!lex || name != name_)
775 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
777 // This is part of the inset proper that is usually swallowed
778 // by LyXText::readInset
781 if (!lex || id != "Include")
782 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
784 InsetInclude inset(params);
786 params = inset.params();
791 InsetIncludeMailer::params2string(InsetCommandParams const & params)
793 InsetInclude inset(params);
795 data << name_ << ' ';
797 data << "\\end_inset\n";