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 "bufferparams.h"
18 #include "BufferView.h"
21 #include "dispatchresult.h"
23 #include "funcrequest.h"
24 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
30 #include "metricsinfo.h"
31 #include "outputparams.h"
33 #include "frontends/Alert.h"
34 #include "frontends/Application.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/lyxalgo.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"
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 fs = boost::filesystem;
88 string const uniqueID()
90 static unsigned int seed = 1000;
91 return "file" + convert<string>(++seed);
97 InsetInclude::InsetInclude(InsetCommandParams const & p)
98 : params_(p), include_label(uniqueID()),
99 preview_(new RenderMonitoredPreview(this)),
102 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
106 InsetInclude::InsetInclude(InsetInclude const & other)
108 params_(other.params_),
109 include_label(other.include_label),
110 preview_(new RenderMonitoredPreview(this)),
113 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
117 InsetInclude::~InsetInclude()
119 InsetIncludeMailer(*this).hideDialog();
123 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
125 switch (cmd.action) {
127 case LFUN_INSET_MODIFY: {
128 InsetCommandParams p;
129 InsetIncludeMailer::string2params(lyx::to_utf8(cmd.argument()), p);
130 if (!p.getCmdName().empty()) {
131 set(p, cur.buffer());
132 cur.buffer().updateBibfilesCache();
138 case LFUN_INSET_DIALOG_UPDATE:
139 InsetIncludeMailer(*this).updateDialog(&cur.bv());
142 case LFUN_MOUSE_RELEASE:
143 InsetIncludeMailer(*this).showDialog(&cur.bv());
147 InsetBase::doDispatch(cur, cmd);
153 bool InsetInclude::getStatus(LCursor & cur, FuncRequest const & cmd,
154 FuncStatus & flag) const
156 switch (cmd.action) {
158 case LFUN_INSET_MODIFY:
159 case LFUN_INSET_DIALOG_UPDATE:
164 return InsetBase::getStatus(cur, cmd, flag);
169 InsetCommandParams const & InsetInclude::params() const
177 /// the type of inclusion
186 Types type(InsetCommandParams const & params)
188 string const command_name = params.getCmdName();
190 if (command_name == "input")
192 if (command_name == "verbatiminput")
194 if (command_name == "verbatiminput*")
200 bool isVerbatim(InsetCommandParams const & params)
202 string const command_name = params.getCmdName();
203 return command_name == "verbatiminput" ||
204 command_name == "verbatiminput*";
208 string const masterFilename(Buffer const & buffer)
210 return buffer.getMasterBuffer()->fileName();
214 string const parentFilename(Buffer const & buffer)
216 return buffer.fileName();
220 string const includedFilename(Buffer const & buffer,
221 InsetCommandParams const & params)
223 return makeAbsPath(params.getContents(),
224 onlyPath(parentFilename(buffer)));
228 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
233 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
238 if (preview_->monitoring())
239 preview_->stopMonitoring();
241 if (type(params_) == INPUT)
242 add_preview(*preview_, *this, buffer);
246 auto_ptr<InsetBase> InsetInclude::doClone() const
248 return auto_ptr<InsetBase>(new InsetInclude(*this));
252 void InsetInclude::write(Buffer const &, ostream & os) const
258 void InsetInclude::write(ostream & os) const
260 os << "Include " << params_.getCommand() << '\n'
261 << "preview " << convert<string>(params_.preview()) << '\n';
265 void InsetInclude::read(Buffer const &, LyXLex & lex)
271 void InsetInclude::read(LyXLex & lex)
277 string const InsetInclude::getScreenLabel(Buffer const &) const
281 switch (type(params_)) {
286 temp += _("Verbatim Input");
289 temp += _("Verbatim Input*");
292 temp += _("Include");
296 temp += lyx::from_ascii(": ");
298 if (params_.getContents().empty())
299 temp += lyx::from_ascii("???");
301 temp += lyx::from_ascii(onlyFilename(params_.getContents()));
304 return lyx::to_utf8(temp);
310 /// return the child buffer if the file is a LyX doc and is loaded
311 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
313 if (isVerbatim(params))
316 string const included_file = includedFilename(buffer, params);
317 if (!isLyXFilename(included_file))
320 return theApp->bufferList().getBuffer(included_file);
324 /// return true if the file is or got loaded.
325 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
327 if (isVerbatim(params))
330 string const included_file = includedFilename(buffer, params);
331 if (!isLyXFilename(included_file))
334 Buffer * buf = theApp->bufferList().getBuffer(included_file);
336 // the readonly flag can/will be wrong, not anymore I think.
337 if (!fs::exists(included_file))
339 buf = theApp->bufferList().newBuffer(included_file);
340 if (!loadLyXFile(buf, included_file))
344 buf->setParentName(parentFilename(buffer));
352 int InsetInclude::latex(Buffer const & buffer, ostream & os,
353 OutputParams const & runparams) const
355 string incfile(params_.getContents());
357 // Do nothing if no file name has been specified
361 string const included_file = includedFilename(buffer, params_);
362 Buffer const * const m_buffer = buffer.getMasterBuffer();
364 // if incfile is relative, make it relative to the master
366 if (!absolutePath(incfile)) {
367 incfile = makeRelPath(included_file,
368 m_buffer->filePath());
371 // write it to a file (so far the complete file)
372 string const exportfile = changeExtension(incfile, ".tex");
373 string const mangled = FileName(changeExtension(included_file,
374 ".tex")).mangledFilename();
375 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
379 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
380 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
381 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
383 if (runparams.inComment || runparams.dryrun)
384 // Don't try to load or copy the file
386 else if (loadIfNeeded(buffer, params_)) {
387 Buffer * tmp = theApp->bufferList().getBuffer(included_file);
389 if (tmp->params().textclass != m_buffer->params().textclass) {
391 docstring text = bformat(_("Included file `%1$s'\n"
392 "has textclass `%2$s'\n"
393 "while parent file has textclass `%3$s'."),
394 makeDisplayPath(included_file),
395 lyx::from_utf8(tmp->params().getLyXTextClass().name()),
396 lyx::from_utf8(m_buffer->params().getLyXTextClass().name()));
397 Alert::warning(_("Different textclasses"), text);
401 tmp->markDepClean(m_buffer->temppath());
404 #warning handle non existing files
405 #warning Second argument is irrelevant!
406 // since only_body is true, makeLaTeXFile will not look at second
407 // argument. Should we set it to string(), or should makeLaTeXFile
408 // make use of it somehow? (JMarc 20031002)
410 tmp->makeLaTeXFile(writefile,
411 onlyPath(masterFilename(buffer)),
414 // Copy the file to the temp dir, so that .aux files etc.
415 // are not created in the original dir. Files included by
416 // this file will be found via input@path, see ../buffer.C.
417 unsigned long const checksum_in = sum(included_file);
418 unsigned long const checksum_out = sum(writefile);
420 if (checksum_in != checksum_out) {
421 if (!copy(included_file, writefile)) {
424 << lyx::to_utf8(bformat(_("Could not copy the file\n%1$s\n"
425 "into the temporary directory."),
426 lyx::from_utf8(included_file)))
433 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
434 "latex" : "pdflatex";
435 if (isVerbatim(params_)) {
436 incfile = latex_path(incfile);
437 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
438 } else if (type(params_) == INPUT) {
439 runparams.exportdata->addExternalFile(tex_format, writefile,
442 // \input wants file with extension (default is .tex)
443 if (!isLyXFilename(included_file)) {
444 incfile = latex_path(incfile);
445 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
447 incfile = changeExtension(incfile, ".tex");
448 incfile = latex_path(incfile);
449 os << '\\' << params_.getCmdName() << '{'
454 runparams.exportdata->addExternalFile(tex_format, writefile,
457 // \include don't want extension and demands that the
458 // file really have .tex
459 incfile = changeExtension(incfile, string());
460 incfile = latex_path(incfile);
461 os << '\\' << params_.getCmdName() << '{'
470 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
471 OutputParams const &) const
473 if (isVerbatim(params_)) {
475 getFileContents(includedFilename(buffer, params_));
477 // Return how many newlines we issued.
478 return int(lyx::count(str.begin(), str.end(), '\n'));
484 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
485 OutputParams const & runparams) const
487 string incfile(params_.getContents());
489 // Do nothing if no file name has been specified
493 string const included_file = includedFilename(buffer, params_);
495 // write it to a file (so far the complete file)
496 string const exportfile = changeExtension(incfile, ".sgml");
497 string writefile = changeExtension(included_file, ".sgml");
499 if (loadIfNeeded(buffer, params_)) {
500 Buffer * tmp = theApp->bufferList().getBuffer(included_file);
502 string const mangled = FileName(writefile).mangledFilename();
503 writefile = makeAbsPath(mangled,
504 buffer.getMasterBuffer()->temppath());
508 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
509 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
510 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
512 tmp->makeDocBookFile(writefile, runparams, true);
515 runparams.exportdata->addExternalFile("docbook", writefile,
517 runparams.exportdata->addExternalFile("docbook-xml", writefile,
520 if (isVerbatim(params_)) {
521 os << "<inlinegraphic fileref=\""
522 << '&' << include_label << ';'
523 << "\" format=\"linespecific\">";
525 os << '&' << include_label << ';';
531 void InsetInclude::validate(LaTeXFeatures & features) const
533 string incfile(params_.getContents());
536 Buffer const & buffer = features.buffer();
538 string const included_file = includedFilename(buffer, params_);
540 if (isLyXFilename(included_file))
541 writefile = changeExtension(included_file, ".sgml");
543 writefile = included_file;
545 if (!features.runparams().nice && !isVerbatim(params_)) {
546 incfile = FileName(writefile).mangledFilename();
547 writefile = makeAbsPath(incfile,
548 buffer.getMasterBuffer()->temppath());
551 features.includeFile(include_label, writefile);
553 if (isVerbatim(params_))
554 features.require("verbatim");
556 // Here we must do the fun stuff...
557 // Load the file in the include if it needs
559 if (loadIfNeeded(buffer, params_)) {
561 Buffer * const tmp = theApp->bufferList().getBuffer(included_file);
563 // We must temporarily change features.buffer,
564 // otherwise it would always be the master buffer,
565 // and nested includes would not work.
566 features.setBuffer(*tmp);
567 tmp->validate(features);
568 features.setBuffer(buffer);
574 void InsetInclude::getLabelList(Buffer const & buffer,
575 std::vector<string> & list) const
577 if (loadIfNeeded(buffer, params_)) {
578 string const included_file = includedFilename(buffer, params_);
579 Buffer * tmp = theApp->bufferList().getBuffer(included_file);
580 tmp->setParentName("");
581 tmp->getLabelList(list);
582 tmp->setParentName(parentFilename(buffer));
587 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
588 std::vector<std::pair<string,string> > & keys) const
590 if (loadIfNeeded(buffer, params_)) {
591 string const included_file = includedFilename(buffer, params_);
592 Buffer * tmp = theApp->bufferList().getBuffer(included_file);
593 tmp->setParentName("");
594 tmp->fillWithBibKeys(keys);
595 tmp->setParentName(parentFilename(buffer));
600 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
602 Buffer * const tmp = getChildBuffer(buffer, params_);
604 tmp->setParentName("");
605 tmp->updateBibfilesCache();
606 tmp->setParentName(parentFilename(buffer));
611 std::vector<string> const &
612 InsetInclude::getBibfilesCache(Buffer const & buffer) const
614 Buffer * const tmp = getChildBuffer(buffer, params_);
616 tmp->setParentName("");
617 std::vector<string> const & cache = tmp->getBibfilesCache();
618 tmp->setParentName(parentFilename(buffer));
621 static std::vector<string> const empty;
626 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
628 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
630 bool use_preview = false;
631 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
632 lyx::graphics::PreviewImage const * pimage =
633 preview_->getPreviewImage(*mi.base.bv->buffer());
634 use_preview = pimage && pimage->image();
638 preview_->metrics(mi, dim);
642 button_.update(getScreenLabel(*mi.base.bv->buffer()),
645 button_.metrics(mi, dim);
648 Box b(0, dim.wid, -dim.asc, dim.des);
655 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
657 setPosCache(pi, x, y);
659 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
661 bool use_preview = false;
662 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
663 lyx::graphics::PreviewImage const * pimage =
664 preview_->getPreviewImage(*pi.base.bv->buffer());
665 use_preview = pimage && pimage->image();
669 preview_->draw(pi, x, y);
671 button_.draw(pi, x, y);
674 bool InsetInclude::display() const
676 return type(params_) != INPUT;
685 void InsetInclude::fileChanged() const
687 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
691 Buffer const & buffer = *buffer_ptr;
692 preview_->removePreview(buffer);
693 add_preview(*preview_.get(), *this, buffer);
694 preview_->startLoading(buffer);
700 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
702 string const included_file = includedFilename(buffer, params);
704 return type(params) == INPUT && params.preview() &&
705 isFileReadable(included_file);
709 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
712 OutputParams runparams;
713 runparams.flavor = OutputParams::LATEX;
714 inset.latex(buffer, os, runparams);
720 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
721 Buffer const & buffer)
723 InsetCommandParams const & params = inset.params();
724 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
725 preview_wanted(params, buffer)) {
726 renderer.setAbsFile(includedFilename(buffer, params));
727 string const snippet = latex_string(inset, buffer);
728 renderer.addPreview(snippet, buffer);
735 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
737 Buffer const & buffer = ploader.buffer();
738 if (preview_wanted(params(), buffer)) {
739 preview_->setAbsFile(includedFilename(buffer, params()));
740 string const snippet = latex_string(*this, buffer);
741 preview_->addPreview(snippet, ploader);
746 string const InsetIncludeMailer::name_("include");
748 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
753 string const InsetIncludeMailer::inset2string(Buffer const &) const
755 return params2string(inset_.params());
759 void InsetIncludeMailer::string2params(string const & in,
760 InsetCommandParams & params)
762 params = InsetCommandParams();
766 istringstream data(in);
772 if (!lex || name != name_)
773 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
775 // This is part of the inset proper that is usually swallowed
776 // by LyXText::readInset
779 if (!lex || id != "Include")
780 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
782 InsetInclude inset(params);
784 params = inset.params();
789 InsetIncludeMailer::params2string(InsetCommandParams const & params)
791 InsetInclude inset(params);
793 data << name_ << ' ';
795 data << "\\end_inset\n";