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());
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 string const InsetInclude::getScreenLabel(Buffer const &) const
282 switch (type(params_)) {
283 case INPUT: temp += _("Input"); break;
284 case VERB: temp += _("Verbatim Input"); break;
285 case VERBAST: temp += _("Verbatim Input*"); break;
286 case INCLUDE: temp += _("Include"); break;
291 if (params_.getContents().empty())
294 temp += onlyFilename(params_.getContents());
302 /// return the child buffer if the file is a LyX doc and is loaded
303 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
305 if (isVerbatim(params))
308 string const included_file = includedFilename(buffer, params);
309 if (!isLyXFilename(included_file))
312 return bufferlist.getBuffer(included_file);
316 /// return true if the file is or got loaded.
317 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
319 if (isVerbatim(params))
322 string const included_file = includedFilename(buffer, params);
323 if (!isLyXFilename(included_file))
326 Buffer * buf = bufferlist.getBuffer(included_file);
328 // the readonly flag can/will be wrong, not anymore I think.
329 if (!fs::exists(included_file))
331 buf = bufferlist.newBuffer(included_file);
332 if (!loadLyXFile(buf, included_file))
336 buf->setParentName(parentFilename(buffer));
344 int InsetInclude::latex(Buffer const & buffer, ostream & os,
345 OutputParams const & runparams) const
347 string incfile(params_.getContents());
349 // Do nothing if no file name has been specified
353 string const included_file = includedFilename(buffer, params_);
354 Buffer const * const m_buffer = buffer.getMasterBuffer();
356 // if incfile is relative, make it relative to the master
358 if (!absolutePath(incfile)) {
359 incfile = makeRelPath(included_file,
360 m_buffer->filePath());
363 // write it to a file (so far the complete file)
364 string const exportfile = changeExtension(incfile, ".tex");
365 string const mangled = FileName(changeExtension(included_file,
366 ".tex")).mangledFilename();
367 string const writefile = makeAbsPath(mangled, m_buffer->temppath());
371 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
372 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
373 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
375 if (runparams.inComment || runparams.dryrun)
376 // Don't try to load or copy the file
378 else if (loadIfNeeded(buffer, params_)) {
379 Buffer * tmp = bufferlist.getBuffer(included_file);
381 if (tmp->params().textclass != m_buffer->params().textclass) {
382 string text = bformat(_("Included file `%1$s'\n"
383 "has textclass `%2$s'\n"
384 "while parent file has textclass `%3$s'."),
385 makeDisplayPath(included_file),
386 tmp->params().getLyXTextClass().name(),
387 m_buffer->params().getLyXTextClass().name());
388 Alert::warning(_("Different textclasses"), text);
392 tmp->markDepClean(m_buffer->temppath());
395 #warning handle non existing files
396 #warning Second argument is irrelevant!
397 // since only_body is true, makeLaTeXFile will not look at second
398 // argument. Should we set it to string(), or should makeLaTeXFile
399 // make use of it somehow? (JMarc 20031002)
401 tmp->makeLaTeXFile(writefile,
402 onlyPath(masterFilename(buffer)),
405 // Copy the file to the temp dir, so that .aux files etc.
406 // are not created in the original dir. Files included by
407 // this file will be found via input@path, see ../buffer.C.
408 unsigned long const checksum_in = sum(included_file);
409 unsigned long const checksum_out = sum(writefile);
411 if (checksum_in != checksum_out) {
412 if (!copy(included_file, writefile)) {
414 << bformat(_("Could not copy the file\n%1$s\n"
415 "into the temporary directory."),
423 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
424 "latex" : "pdflatex";
425 if (isVerbatim(params_)) {
426 incfile = latex_path(incfile);
427 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
428 } else if (type(params_) == INPUT) {
429 runparams.exportdata->addExternalFile(tex_format, writefile,
432 // \input wants file with extension (default is .tex)
433 if (!isLyXFilename(included_file)) {
434 incfile = latex_path(incfile);
435 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
437 incfile = changeExtension(incfile, ".tex");
438 incfile = latex_path(incfile);
439 os << '\\' << params_.getCmdName() << '{'
444 runparams.exportdata->addExternalFile(tex_format, writefile,
447 // \include don't want extension and demands that the
448 // file really have .tex
449 incfile = changeExtension(incfile, string());
450 incfile = latex_path(incfile);
451 os << '\\' << params_.getCmdName() << '{'
460 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
461 OutputParams const &) const
463 if (isVerbatim(params_))
464 os << getFileContents(includedFilename(buffer, params_));
469 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
470 OutputParams const & runparams) const
472 string incfile(params_.getContents());
474 // Do nothing if no file name has been specified
478 string const included_file = includedFilename(buffer, params_);
480 // write it to a file (so far the complete file)
481 string const exportfile = changeExtension(incfile, ".sgml");
482 string writefile = changeExtension(included_file, ".sgml");
484 if (loadIfNeeded(buffer, params_)) {
485 Buffer * tmp = bufferlist.getBuffer(included_file);
487 string const mangled = FileName(writefile).mangledFilename();
488 writefile = makeAbsPath(mangled,
489 buffer.getMasterBuffer()->temppath());
493 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
494 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
495 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
497 tmp->makeDocBookFile(writefile, runparams, true);
500 runparams.exportdata->addExternalFile("docbook", writefile,
502 runparams.exportdata->addExternalFile("docbook-xml", writefile,
505 if (isVerbatim(params_)) {
506 os << "<inlinegraphic fileref=\""
507 << '&' << include_label << ';'
508 << "\" format=\"linespecific\">";
510 os << '&' << include_label << ';';
516 void InsetInclude::validate(LaTeXFeatures & features) const
518 string incfile(params_.getContents());
521 Buffer const & buffer = features.buffer();
523 string const included_file = includedFilename(buffer, params_);
525 if (isLyXFilename(included_file))
526 writefile = changeExtension(included_file, ".sgml");
528 writefile = included_file;
530 if (!features.runparams().nice && !isVerbatim(params_)) {
531 incfile = FileName(writefile).mangledFilename();
532 writefile = makeAbsPath(incfile,
533 buffer.getMasterBuffer()->temppath());
536 features.includeFile(include_label, writefile);
538 if (isVerbatim(params_))
539 features.require("verbatim");
541 // Here we must do the fun stuff...
542 // Load the file in the include if it needs
544 if (loadIfNeeded(buffer, params_)) {
546 Buffer * const tmp = bufferlist.getBuffer(included_file);
548 // We must temporarily change features.buffer,
549 // otherwise it would always be the master buffer,
550 // and nested includes would not work.
551 features.setBuffer(*tmp);
552 tmp->validate(features);
553 features.setBuffer(buffer);
559 void InsetInclude::getLabelList(Buffer const & buffer,
560 std::vector<string> & list) const
562 if (loadIfNeeded(buffer, params_)) {
563 string const included_file = includedFilename(buffer, params_);
564 Buffer * tmp = bufferlist.getBuffer(included_file);
565 tmp->setParentName("");
566 tmp->getLabelList(list);
567 tmp->setParentName(parentFilename(buffer));
572 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
573 std::vector<std::pair<string,string> > & keys) const
575 if (loadIfNeeded(buffer, params_)) {
576 string const included_file = includedFilename(buffer, params_);
577 Buffer * tmp = bufferlist.getBuffer(included_file);
578 tmp->setParentName("");
579 tmp->fillWithBibKeys(keys);
580 tmp->setParentName(parentFilename(buffer));
585 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
587 Buffer * const tmp = getChildBuffer(buffer, params_);
589 tmp->setParentName("");
590 tmp->updateBibfilesCache();
591 tmp->setParentName(parentFilename(buffer));
596 std::vector<string> const &
597 InsetInclude::getBibfilesCache(Buffer const & buffer) const
599 Buffer * const tmp = getChildBuffer(buffer, params_);
601 tmp->setParentName("");
602 std::vector<string> const & cache = tmp->getBibfilesCache();
603 tmp->setParentName(parentFilename(buffer));
606 static std::vector<string> const empty;
611 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
613 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
615 bool use_preview = false;
616 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
617 lyx::graphics::PreviewImage const * pimage =
618 preview_->getPreviewImage(*mi.base.bv->buffer());
619 use_preview = pimage && pimage->image();
623 preview_->metrics(mi, dim);
627 button_.update(getScreenLabel(*mi.base.bv->buffer()),
630 button_.metrics(mi, dim);
633 Box b(0, dim.wid, -dim.asc, dim.des);
640 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
642 setPosCache(pi, x, y);
644 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
646 bool use_preview = false;
647 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
648 lyx::graphics::PreviewImage const * pimage =
649 preview_->getPreviewImage(*pi.base.bv->buffer());
650 use_preview = pimage && pimage->image();
654 preview_->draw(pi, x, y);
656 button_.draw(pi, x, y);
659 bool InsetInclude::display() const
661 return type(params_) != INPUT;
670 void InsetInclude::fileChanged() const
672 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
676 Buffer const & buffer = *buffer_ptr;
677 preview_->removePreview(buffer);
678 add_preview(*preview_.get(), *this, buffer);
679 preview_->startLoading(buffer);
685 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
687 string const included_file = includedFilename(buffer, params);
689 return type(params) == INPUT && params.preview() &&
690 isFileReadable(included_file);
694 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
697 OutputParams runparams;
698 runparams.flavor = OutputParams::LATEX;
699 inset.latex(buffer, os, runparams);
705 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
706 Buffer const & buffer)
708 InsetCommandParams const & params = inset.params();
709 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
710 preview_wanted(params, buffer)) {
711 renderer.setAbsFile(includedFilename(buffer, params));
712 string const snippet = latex_string(inset, buffer);
713 renderer.addPreview(snippet, buffer);
720 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
722 Buffer const & buffer = ploader.buffer();
723 if (preview_wanted(params(), buffer)) {
724 preview_->setAbsFile(includedFilename(buffer, params()));
725 string const snippet = latex_string(*this, buffer);
726 preview_->addPreview(snippet, ploader);
731 string const InsetIncludeMailer::name_("include");
733 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
738 string const InsetIncludeMailer::inset2string(Buffer const &) const
740 return params2string(inset_.params());
744 void InsetIncludeMailer::string2params(string const & in,
745 InsetCommandParams & params)
747 params = InsetCommandParams();
751 istringstream data(in);
757 if (!lex || name != name_)
758 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
760 // This is part of the inset proper that is usually swallowed
761 // by LyXText::readInset
764 if (!lex || id != "Include")
765 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
767 InsetInclude inset(params);
769 params = inset.params();
774 InsetIncludeMailer::params2string(InsetCommandParams const & params)
776 InsetInclude inset(params);
778 data << name_ << ' ';
780 data << "\\end_inset\n";