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"
59 using support::addName;
60 using support::absolutePath;
61 using support::bformat;
62 using support::changeExtension;
63 using support::contains;
65 using support::FileName;
66 using support::getFileContents;
67 using support::isFileReadable;
68 using support::isLyXFilename;
69 using support::latex_path;
70 using support::makeAbsPath;
71 using support::makeDisplayPath;
72 using support::makeRelPath;
73 using support::onlyFilename;
74 using support::onlyPath;
81 using std::istringstream;
83 using std::ostringstream;
85 namespace Alert = frontend::Alert;
86 namespace fs = boost::filesystem;
91 docstring const uniqueID()
93 static unsigned int seed = 1000;
94 return "file" + convert<docstring>(++seed);
100 InsetInclude::InsetInclude(InsetCommandParams const & p)
101 : params_(p), include_label(uniqueID()),
102 preview_(new RenderMonitoredPreview(this)),
105 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
109 InsetInclude::InsetInclude(InsetInclude const & other)
111 params_(other.params_),
112 include_label(other.include_label),
113 preview_(new RenderMonitoredPreview(this)),
116 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
120 InsetInclude::~InsetInclude()
122 InsetIncludeMailer(*this).hideDialog();
126 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
128 switch (cmd.action) {
130 case LFUN_INSET_MODIFY: {
131 InsetCommandParams p("include");
132 InsetIncludeMailer::string2params(to_utf8(cmd.argument()), p);
133 if (!p.getCmdName().empty()) {
134 set(p, cur.buffer());
135 cur.buffer().updateBibfilesCache();
141 case LFUN_INSET_DIALOG_UPDATE:
142 InsetIncludeMailer(*this).updateDialog(&cur.bv());
145 case LFUN_MOUSE_RELEASE:
146 InsetIncludeMailer(*this).showDialog(&cur.bv());
150 InsetBase::doDispatch(cur, cmd);
156 bool InsetInclude::getStatus(LCursor & cur, FuncRequest const & cmd,
157 FuncStatus & flag) const
159 switch (cmd.action) {
161 case LFUN_INSET_MODIFY:
162 case LFUN_INSET_DIALOG_UPDATE:
167 return InsetBase::getStatus(cur, cmd, flag);
172 InsetCommandParams const & InsetInclude::params() const
180 /// the type of inclusion
189 Types type(InsetCommandParams const & params)
191 string const command_name = params.getCmdName();
193 if (command_name == "input")
195 if (command_name == "verbatiminput")
197 if (command_name == "verbatiminput*")
203 bool isVerbatim(InsetCommandParams const & params)
205 string const command_name = params.getCmdName();
206 return command_name == "verbatiminput" ||
207 command_name == "verbatiminput*";
211 string const masterFilename(Buffer const & buffer)
213 return buffer.getMasterBuffer()->fileName();
217 string const parentFilename(Buffer const & buffer)
219 return buffer.fileName();
223 string const includedFilename(Buffer const & buffer,
224 InsetCommandParams const & params)
226 return makeAbsPath(to_utf8(params["filename"]),
227 onlyPath(parentFilename(buffer)));
231 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
236 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
241 if (preview_->monitoring())
242 preview_->stopMonitoring();
244 if (type(params_) == INPUT)
245 add_preview(*preview_, *this, buffer);
249 auto_ptr<InsetBase> InsetInclude::doClone() const
251 return auto_ptr<InsetBase>(new InsetInclude(*this));
255 void InsetInclude::write(Buffer const &, ostream & os) const
261 void InsetInclude::write(ostream & os) const
263 os << "Include " << to_utf8(params_.getCommand()) << '\n'
264 << "preview " << convert<string>(params_.preview()) << '\n';
268 void InsetInclude::read(Buffer const &, LyXLex & lex)
274 void InsetInclude::read(LyXLex & lex)
278 string const command = lex.getString();
279 params_.scanCommand(command);
284 token = lex.getString();
285 if (token == "\\end_inset")
287 if (token == "preview") {
289 params_.preview(lex.getBool());
291 lex.printError("Unknown parameter name `$$Token' for command " + params_.getCmdName());
293 if (token != "\\end_inset") {
294 lex.printError("Missing \\end_inset at this point. "
300 docstring const InsetInclude::getScreenLabel(Buffer const &) const
304 switch (type(params_)) {
309 temp += _("Verbatim Input");
312 temp += _("Verbatim Input*");
315 temp += _("Include");
321 if (params_["filename"].empty())
324 // FIXME: We don't know the encoding of the filename
325 temp += from_ascii(onlyFilename(to_utf8(params_["filename"])));
333 /// return the child buffer if the file is a LyX doc and is loaded
334 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
336 if (isVerbatim(params))
339 string const included_file = includedFilename(buffer, params);
340 if (!isLyXFilename(included_file))
343 return theBufferList().getBuffer(included_file);
347 /// return true if the file is or got loaded.
348 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
350 if (isVerbatim(params))
353 string const included_file = includedFilename(buffer, params);
354 if (!isLyXFilename(included_file))
357 Buffer * buf = theBufferList().getBuffer(included_file);
359 // the readonly flag can/will be wrong, not anymore I think.
360 if (!fs::exists(included_file))
362 buf = theBufferList().newBuffer(included_file);
363 if (!loadLyXFile(buf, included_file))
367 buf->setParentName(parentFilename(buffer));
375 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
376 OutputParams const & runparams) const
378 string incfile(to_utf8(params_["filename"]));
380 // Do nothing if no file name has been specified
384 string const included_file = includedFilename(buffer, params_);
385 Buffer const * const m_buffer = buffer.getMasterBuffer();
387 // if incfile is relative, make it relative to the master
389 if (!absolutePath(incfile)) {
390 incfile = makeRelPath(included_file,
391 m_buffer->filePath());
394 // write it to a file (so far the complete file)
395 string const exportfile = changeExtension(incfile, ".tex");
396 string const mangled = FileName(changeExtension(included_file,
397 ".tex")).mangledFilename();
398 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
402 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
403 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
404 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
406 if (runparams.inComment || runparams.dryrun)
407 // Don't try to load or copy the file
409 else if (loadIfNeeded(buffer, params_)) {
410 Buffer * tmp = theBufferList().getBuffer(included_file);
412 if (tmp->params().textclass != m_buffer->params().textclass) {
414 docstring text = bformat(_("Included file `%1$s'\n"
415 "has textclass `%2$s'\n"
416 "while parent file has textclass `%3$s'."),
417 makeDisplayPath(included_file),
418 from_utf8(tmp->params().getLyXTextClass().name()),
419 from_utf8(m_buffer->params().getLyXTextClass().name()));
420 Alert::warning(_("Different textclasses"), text);
424 tmp->markDepClean(m_buffer->temppath());
427 #warning handle non existing files
428 #warning Second argument is irrelevant!
429 // since only_body is true, makeLaTeXFile will not look at second
430 // argument. Should we set it to string(), or should makeLaTeXFile
431 // make use of it somehow? (JMarc 20031002)
433 tmp->makeLaTeXFile(writefile,
434 onlyPath(masterFilename(buffer)),
437 // Copy the file to the temp dir, so that .aux files etc.
438 // are not created in the original dir. Files included by
439 // this file will be found via input@path, see ../buffer.C.
440 unsigned long const checksum_in = sum(included_file);
441 unsigned long const checksum_out = sum(writefile);
443 if (checksum_in != checksum_out) {
444 if (!copy(included_file, writefile)) {
447 << to_utf8(bformat(_("Could not copy the file\n%1$s\n"
448 "into the temporary directory."),
449 from_utf8(included_file)))
456 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
457 "latex" : "pdflatex";
458 if (isVerbatim(params_)) {
459 incfile = latex_path(incfile);
461 os << '\\' << from_ascii(params_.getCmdName()) << '{'
462 << from_utf8(incfile) << '}';
463 } else if (type(params_) == INPUT) {
464 runparams.exportdata->addExternalFile(tex_format, writefile,
467 // \input wants file with extension (default is .tex)
468 if (!isLyXFilename(included_file)) {
469 incfile = latex_path(incfile);
471 os << '\\' << from_ascii(params_.getCmdName())
472 << '{' << from_utf8(incfile) << '}';
474 incfile = changeExtension(incfile, ".tex");
475 incfile = latex_path(incfile);
477 os << '\\' << from_ascii(params_.getCmdName())
478 << '{' << from_utf8(incfile) << '}';
481 runparams.exportdata->addExternalFile(tex_format, writefile,
484 // \include don't want extension and demands that the
485 // file really have .tex
486 incfile = changeExtension(incfile, string());
487 incfile = latex_path(incfile);
489 os << '\\' << from_ascii(params_.getCmdName()) << '{'
490 << from_utf8(incfile) << '}';
497 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
498 OutputParams const &) const
500 if (isVerbatim(params_)) {
501 // FIXME: We don't know the encoding of the file
502 docstring const str = from_utf8(
503 getFileContents(includedFilename(buffer, params_)));
505 // Return how many newlines we issued.
506 return int(lyx::count(str.begin(), str.end(), '\n'));
512 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
513 OutputParams const & runparams) const
515 string incfile = to_utf8(params_["filename"]);
517 // Do nothing if no file name has been specified
521 string const included_file = includedFilename(buffer, params_);
523 // write it to a file (so far the complete file)
524 string const exportfile = changeExtension(incfile, ".sgml");
525 string writefile = changeExtension(included_file, ".sgml");
527 if (loadIfNeeded(buffer, params_)) {
528 Buffer * tmp = theBufferList().getBuffer(included_file);
530 string const mangled = FileName(writefile).mangledFilename();
531 writefile = makeAbsPath(mangled,
532 buffer.getMasterBuffer()->temppath());
536 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
537 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
538 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
540 tmp->makeDocBookFile(writefile, runparams, true);
543 runparams.exportdata->addExternalFile("docbook", writefile,
545 runparams.exportdata->addExternalFile("docbook-xml", writefile,
548 if (isVerbatim(params_)) {
549 os << "<inlinegraphic fileref=\""
550 << '&' << include_label << ';'
551 << "\" format=\"linespecific\">";
553 os << '&' << include_label << ';';
559 void InsetInclude::validate(LaTeXFeatures & features) const
561 string incfile(to_utf8(params_["filename"]));
564 Buffer const & buffer = features.buffer();
566 string const included_file = includedFilename(buffer, params_);
568 if (isLyXFilename(included_file))
569 writefile = changeExtension(included_file, ".sgml");
571 writefile = included_file;
573 if (!features.runparams().nice && !isVerbatim(params_)) {
574 incfile = FileName(writefile).mangledFilename();
575 writefile = makeAbsPath(incfile,
576 buffer.getMasterBuffer()->temppath());
579 features.includeFile(include_label, writefile);
581 if (isVerbatim(params_))
582 features.require("verbatim");
584 // Here we must do the fun stuff...
585 // Load the file in the include if it needs
587 if (loadIfNeeded(buffer, params_)) {
589 Buffer * const tmp = theBufferList().getBuffer(included_file);
591 // We must temporarily change features.buffer,
592 // otherwise it would always be the master buffer,
593 // and nested includes would not work.
594 features.setBuffer(*tmp);
595 tmp->validate(features);
596 features.setBuffer(buffer);
602 void InsetInclude::getLabelList(Buffer const & buffer,
603 std::vector<docstring> & list) const
605 if (loadIfNeeded(buffer, params_)) {
606 string const included_file = includedFilename(buffer, params_);
607 Buffer * tmp = theBufferList().getBuffer(included_file);
608 tmp->setParentName("");
609 tmp->getLabelList(list);
610 tmp->setParentName(parentFilename(buffer));
615 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
616 std::vector<std::pair<string,string> > & keys) const
618 if (loadIfNeeded(buffer, params_)) {
619 string const included_file = includedFilename(buffer, params_);
620 Buffer * tmp = theBufferList().getBuffer(included_file);
621 tmp->setParentName("");
622 tmp->fillWithBibKeys(keys);
623 tmp->setParentName(parentFilename(buffer));
628 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
630 Buffer * const tmp = getChildBuffer(buffer, params_);
632 tmp->setParentName("");
633 tmp->updateBibfilesCache();
634 tmp->setParentName(parentFilename(buffer));
639 std::vector<string> const &
640 InsetInclude::getBibfilesCache(Buffer const & buffer) const
642 Buffer * const tmp = getChildBuffer(buffer, params_);
644 tmp->setParentName("");
645 std::vector<string> const & cache = tmp->getBibfilesCache();
646 tmp->setParentName(parentFilename(buffer));
649 static std::vector<string> const empty;
654 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
656 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
658 bool use_preview = false;
659 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
660 graphics::PreviewImage const * pimage =
661 preview_->getPreviewImage(*mi.base.bv->buffer());
662 use_preview = pimage && pimage->image();
666 preview_->metrics(mi, dim);
670 button_.update(getScreenLabel(*mi.base.bv->buffer()),
673 button_.metrics(mi, dim);
676 Box b(0, dim.wid, -dim.asc, dim.des);
683 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
685 setPosCache(pi, x, y);
687 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
689 bool use_preview = false;
690 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
691 graphics::PreviewImage const * pimage =
692 preview_->getPreviewImage(*pi.base.bv->buffer());
693 use_preview = pimage && pimage->image();
697 preview_->draw(pi, x, y);
699 button_.draw(pi, x, y);
702 bool InsetInclude::display() const
704 return type(params_) != INPUT;
713 void InsetInclude::fileChanged() const
715 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
719 Buffer const & buffer = *buffer_ptr;
720 preview_->removePreview(buffer);
721 add_preview(*preview_.get(), *this, buffer);
722 preview_->startLoading(buffer);
728 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
730 string const included_file = includedFilename(buffer, params);
732 return type(params) == INPUT && params.preview() &&
733 isFileReadable(included_file);
737 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
740 OutputParams runparams;
741 runparams.flavor = OutputParams::LATEX;
742 inset.latex(buffer, os, runparams);
748 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
749 Buffer const & buffer)
751 InsetCommandParams const & params = inset.params();
752 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
753 preview_wanted(params, buffer)) {
754 renderer.setAbsFile(includedFilename(buffer, params));
755 docstring const snippet = latex_string(inset, buffer);
756 renderer.addPreview(snippet, buffer);
763 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
765 Buffer const & buffer = ploader.buffer();
766 if (preview_wanted(params(), buffer)) {
767 preview_->setAbsFile(includedFilename(buffer, params()));
768 docstring const snippet = latex_string(*this, buffer);
769 preview_->addPreview(snippet, ploader);
774 string const InsetIncludeMailer::name_("include");
776 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
781 string const InsetIncludeMailer::inset2string(Buffer const &) const
783 return params2string(inset_.params());
787 void InsetIncludeMailer::string2params(string const & in,
788 InsetCommandParams & params)
794 istringstream data(in);
800 if (!lex || name != name_)
801 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
803 // This is part of the inset proper that is usually swallowed
804 // by LyXText::readInset
807 if (!lex || id != "Include")
808 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
810 InsetInclude inset(params);
812 params = inset.params();
817 InsetIncludeMailer::params2string(InsetCommandParams const & params)
819 InsetInclude inset(params);
821 data << name_ << ' ';
823 data << "\\end_inset\n";