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"
26 #include "LaTeXFeatures.h"
30 #include "metricsinfo.h"
31 #include "outputparams.h"
33 #include "frontends/Alert.h"
34 #include "frontends/LyXView.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/FileInfo.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/tostr.h"
49 #include <boost/bind.hpp>
51 #include "support/std_ostream.h"
52 #include "support/std_sstream.h"
54 using lyx::support::AddName;
55 using lyx::support::AbsolutePath;
56 using lyx::support::bformat;
57 using lyx::support::ChangeExtension;
58 using lyx::support::contains;
59 using lyx::support::copy;
60 using lyx::support::FileInfo;
61 using lyx::support::FileName;
62 using lyx::support::GetFileContents;
63 using lyx::support::IsFileReadable;
64 using lyx::support::IsLyXFilename;
65 using lyx::support::MakeAbsPath;
66 using lyx::support::MakeDisplayPath;
67 using lyx::support::MakeRelPath;
68 using lyx::support::OnlyFilename;
69 using lyx::support::OnlyPath;
70 using lyx::support::subst;
71 using lyx::support::sum;
76 using std::istringstream;
78 using std::ostringstream;
81 extern BufferList bufferlist;
86 string const uniqueID()
88 static unsigned int seed = 1000;
89 return "file" + tostr(++seed);
95 InsetInclude::InsetInclude(InsetCommandParams const & p)
96 : params_(p), include_label(uniqueID()),
97 preview_(new RenderMonitoredPreview(this)),
100 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
104 InsetInclude::InsetInclude(InsetInclude const & other)
106 params_(other.params_),
107 include_label(other.include_label),
108 preview_(new RenderMonitoredPreview(this)),
109 set_label_(other.set_label_)
111 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
115 InsetInclude::~InsetInclude()
117 InsetIncludeMailer(*this).hideDialog();
121 void InsetInclude::priv_dispatch(LCursor & cur, FuncRequest & cmd)
123 switch (cmd.action) {
125 case LFUN_INSET_MODIFY: {
126 InsetCommandParams p;
127 InsetIncludeMailer::string2params(cmd.argument, p);
128 if (!p.getCmdName().empty()) {
129 set(p, cur.buffer());
135 case LFUN_INSET_DIALOG_UPDATE:
136 InsetIncludeMailer(*this).updateDialog(&cur.bv());
139 case LFUN_MOUSE_RELEASE:
140 if (button_.box().contains(cmd.x, cmd.y))
141 InsetIncludeMailer(*this).showDialog(&cur.bv());
144 case LFUN_INSET_DIALOG_SHOW:
145 InsetIncludeMailer(*this).showDialog(&cur.bv());
149 InsetOld::priv_dispatch(cur, cmd);
155 InsetCommandParams const & InsetInclude::params() const
163 /// the type of inclusion
172 Types type(InsetCommandParams const & params)
174 string const command_name = params.getCmdName();
176 if (command_name == "input")
178 if (command_name == "verbatiminput")
180 if (command_name == "verbatiminput*")
186 bool isVerbatim(InsetCommandParams const & params)
188 string const command_name = params.getCmdName();
189 return command_name == "verbatiminput" ||
190 command_name == "verbatiminput*";
194 string const masterFilename(Buffer const & buffer)
196 return buffer.getMasterBuffer()->fileName();
200 string const parentFilename(Buffer const & buffer)
202 return buffer.fileName();
206 string const includedFilename(Buffer const & buffer,
207 InsetCommandParams const & params)
209 return MakeAbsPath(params.getContents(),
210 OnlyPath(parentFilename(buffer)));
214 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
219 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
224 if (preview_->monitoring())
225 preview_->stopMonitoring();
227 if (type(params_) == INPUT)
228 add_preview(*preview_, *this, buffer);
232 auto_ptr<InsetBase> InsetInclude::clone() const
234 return auto_ptr<InsetBase>(new InsetInclude(*this));
238 void InsetInclude::write(Buffer const &, ostream & os) const
244 void InsetInclude::write(ostream & os) const
246 os << "Include " << params_.getCommand() << '\n'
247 << "preview " << tostr(params_.preview()) << '\n';
251 void InsetInclude::read(Buffer const &, LyXLex & lex)
257 void InsetInclude::read(LyXLex & lex)
263 string const InsetInclude::getScreenLabel(Buffer const &) const
267 switch (type(params_)) {
268 case INPUT: temp += _("Input"); break;
269 case VERB: temp += _("Verbatim Input"); break;
270 case VERBAST: temp += _("Verbatim Input*"); break;
271 case INCLUDE: temp += _("Include"); break;
276 if (params_.getContents().empty())
279 temp += OnlyFilename(params_.getContents());
287 /// return true if the file is or got loaded.
288 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
290 if (isVerbatim(params))
293 string const included_file = includedFilename(buffer, params);
294 if (!IsLyXFilename(included_file))
297 Buffer * buf = bufferlist.getBuffer(included_file);
299 // the readonly flag can/will be wrong, not anymore I think.
300 FileInfo finfo(included_file);
303 buf = bufferlist.newBuffer(included_file);
304 if (!loadLyXFile(buf, included_file))
308 buf->setParentName(parentFilename(buffer));
316 int InsetInclude::latex(Buffer const & buffer, ostream & os,
317 OutputParams const & runparams) const
319 string incfile(params_.getContents());
321 // Do nothing if no file name has been specified
325 string const included_file = includedFilename(buffer, params_);
326 Buffer const * const m_buffer = buffer.getMasterBuffer();
328 // if incfile is relative, make it relative to the master
330 if (!AbsolutePath(incfile)) {
331 incfile = MakeRelPath(included_file,
332 m_buffer->filePath());
335 // write it to a file (so far the complete file)
336 string const exportfile = ChangeExtension(incfile, ".tex");
337 string const mangled = FileName(ChangeExtension(included_file,
338 ".tex")).mangledFilename();
339 string const writefile = MakeAbsPath(mangled, m_buffer->temppath());
343 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
344 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
345 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
347 if (loadIfNeeded(buffer, params_)) {
348 Buffer * tmp = bufferlist.getBuffer(included_file);
350 if (tmp->params().textclass != m_buffer->params().textclass) {
351 string text = bformat(_("Included file `%1$s'\n"
352 "has textclass `%2$s'\n"
353 "while parent file has textclass `%3$s'."),
354 MakeDisplayPath(included_file),
355 tmp->params().getLyXTextClass().name(),
356 m_buffer->params().getLyXTextClass().name());
357 Alert::warning(_("Different textclasses"), text);
361 tmp->markDepClean(m_buffer->temppath());
364 #warning Second argument is irrelevant!
365 // since only_body is true, makeLaTeXFile will not look at second
366 // argument. Should we set it to string(), or should makeLaTeXFile
367 // make use of it somehow? (JMarc 20031002)
369 tmp->makeLaTeXFile(writefile,
370 OnlyPath(masterFilename(buffer)),
373 // Copy the file to the temp dir, so that .aux files etc.
374 // are not created in the original dir. Files included by
375 // this file will be found via input@path, see ../buffer.C.
376 unsigned long const checksum_in = sum(included_file);
377 unsigned long const checksum_out = sum(writefile);
379 if (checksum_in != checksum_out) {
380 if (!copy(included_file, writefile)) {
382 << bformat(_("Could not copy the file\n%1$s\n"
383 "into the temporary directory."),
391 if (isVerbatim(params_)) {
392 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
393 } else if (type(params_) == INPUT) {
394 runparams.exportdata->addExternalFile("latex", writefile,
397 // \input wants file with extension (default is .tex)
398 if (!IsLyXFilename(included_file)) {
399 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
401 os << '\\' << params_.getCmdName() << '{'
402 << ChangeExtension(incfile, ".tex")
406 runparams.exportdata->addExternalFile("latex", writefile,
409 // \include don't want extension and demands that the
410 // file really have .tex
411 os << '\\' << params_.getCmdName() << '{'
412 << ChangeExtension(incfile, string())
420 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
421 OutputParams const &) const
423 if (isVerbatim(params_))
424 os << GetFileContents(includedFilename(buffer, params_));
429 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
430 OutputParams const & runparams) const
432 string incfile(params_.getContents());
434 // Do nothing if no file name has been specified
438 string const included_file = includedFilename(buffer, params_);
440 // write it to a file (so far the complete file)
441 string const exportfile = ChangeExtension(incfile, ".sgml");
442 string writefile = ChangeExtension(included_file, ".sgml");
444 if (loadIfNeeded(buffer, params_)) {
445 Buffer * tmp = bufferlist.getBuffer(included_file);
447 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
448 buffer.getMasterBuffer()->temppath());
452 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
453 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
454 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
456 tmp->makeLinuxDocFile(writefile, runparams, true);
459 if (isVerbatim(params_)) {
461 << GetFileContents(included_file)
464 runparams.exportdata->addExternalFile("linuxdoc", writefile,
466 os << '&' << include_label << ';';
473 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
474 OutputParams const & runparams) const
476 string incfile(params_.getContents());
478 // Do nothing if no file name has been specified
482 string const included_file = includedFilename(buffer, params_);
484 // write it to a file (so far the complete file)
485 string const exportfile = ChangeExtension(incfile, ".sgml");
486 string writefile = ChangeExtension(included_file, ".sgml");
488 if (loadIfNeeded(buffer, params_)) {
489 Buffer * tmp = bufferlist.getBuffer(included_file);
491 string const mangled = FileName(writefile).mangledFilename();
492 writefile = MakeAbsPath(mangled,
493 buffer.getMasterBuffer()->temppath());
497 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
498 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
499 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
501 tmp->makeDocBookFile(writefile, runparams, true);
504 runparams.exportdata->addExternalFile("docbook", writefile,
506 runparams.exportdata->addExternalFile("docbook-xml", writefile,
509 if (isVerbatim(params_)) {
510 os << "<inlinegraphic fileref=\""
511 << '&' << include_label << ';'
512 << "\" format=\"linespecific\">";
514 os << '&' << include_label << ';';
520 void InsetInclude::validate(LaTeXFeatures & features) const
522 string incfile(params_.getContents());
525 Buffer const & buffer = features.buffer();
527 string const included_file = includedFilename(buffer, params_);
529 if (IsLyXFilename(included_file))
530 writefile = ChangeExtension(included_file, ".sgml");
532 writefile = included_file;
534 if (!features.nice() && !isVerbatim(params_)) {
535 incfile = FileName(writefile).mangledFilename();
536 writefile = MakeAbsPath(incfile,
537 buffer.getMasterBuffer()->temppath());
540 features.includeFile(include_label, writefile);
542 if (isVerbatim(params_))
543 features.require("verbatim");
545 // Here we must do the fun stuff...
546 // Load the file in the include if it needs
548 if (loadIfNeeded(buffer, params_)) {
550 Buffer * const tmp = bufferlist.getBuffer(included_file);
552 // We must temporarily change features.buffer,
553 // otherwise it would always be the master buffer,
554 // and nested includes would not work.
555 features.setBuffer(*tmp);
556 tmp->validate(features);
557 features.setBuffer(buffer);
563 void InsetInclude::getLabelList(Buffer const & buffer,
564 std::vector<string> & list) const
566 if (loadIfNeeded(buffer, params_)) {
567 string const included_file = includedFilename(buffer, params_);
568 Buffer * tmp = bufferlist.getBuffer(included_file);
569 tmp->setParentName("");
570 tmp->getLabelList(list);
571 tmp->setParentName(parentFilename(buffer));
576 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
577 std::vector<std::pair<string,string> > & keys) const
579 if (loadIfNeeded(buffer, params_)) {
580 string const included_file = includedFilename(buffer, params_);
581 Buffer * tmp = bufferlist.getBuffer(included_file);
582 tmp->setParentName("");
583 tmp->fillWithBibKeys(keys);
584 tmp->setParentName(parentFilename(buffer));
589 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
591 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
593 bool use_preview = false;
594 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
595 lyx::graphics::PreviewImage const * pimage =
596 preview_->getPreviewImage(*mi.base.bv->buffer());
597 use_preview = pimage && pimage->image();
601 preview_->metrics(mi, dim);
605 button_.update(getScreenLabel(*mi.base.bv->buffer()),
606 editable() != NOT_EDITABLE);
608 button_.metrics(mi, dim);
610 int center_indent = type(params_) == INPUT ?
611 0 : (mi.base.textwidth - dim.wid) / 2;
612 Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
615 dim.wid = mi.base.textwidth;
620 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
622 setPosCache(pi, x, y);
624 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
626 bool use_preview = false;
627 if (RenderPreview::status() == LyXRC::PREVIEW_OFF) {
628 lyx::graphics::PreviewImage const * pimage =
629 preview_->getPreviewImage(*pi.base.bv->buffer());
630 use_preview = pimage && pimage->image();
634 preview_->draw(pi, x + button_.box().x1, y);
636 button_.draw(pi, x + button_.box().x1, y);
644 void InsetInclude::fileChanged() const
646 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
650 Buffer const & buffer = *buffer_ptr;
651 preview_->removePreview(buffer);
652 add_preview(*preview_.get(), *this, buffer);
653 preview_->startLoading(buffer);
659 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
661 string const included_file = includedFilename(buffer, params);
663 return type(params) == INPUT && params.preview() &&
664 IsFileReadable(included_file);
668 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
671 OutputParams runparams;
672 runparams.flavor = OutputParams::LATEX;
673 inset.latex(buffer, os, runparams);
679 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
680 Buffer const & buffer)
682 InsetCommandParams const & params = inset.params();
683 if (RenderPreview::status() == LyXRC::PREVIEW_OFF &&
684 preview_wanted(params, buffer)) {
685 renderer.setAbsFile(includedFilename(buffer, params));
686 string const snippet = latex_string(inset, buffer);
687 renderer.addPreview(snippet, buffer);
694 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
696 Buffer const & buffer = ploader.buffer();
697 if (preview_wanted(params(), buffer)) {
698 preview_->setAbsFile(includedFilename(buffer, params()));
699 string const snippet = latex_string(*this, buffer);
700 preview_->addPreview(snippet, ploader);
705 string const InsetIncludeMailer::name_("include");
707 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
712 string const InsetIncludeMailer::inset2string(Buffer const &) const
714 return params2string(inset_.params());
718 void InsetIncludeMailer::string2params(string const & in,
719 InsetCommandParams & params)
721 params = InsetCommandParams();
725 istringstream data(in);
731 if (!lex || name != name_)
732 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
734 // This is part of the inset proper that is usually swallowed
735 // by LyXText::readInset
738 if (!lex || id != "Include")
739 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
741 InsetInclude inset(params);
743 params = inset.params();
748 InsetIncludeMailer::params2string(InsetCommandParams const & params)
750 InsetInclude inset(params);
752 data << name_ << ' ';
754 data << "\\end_inset\n";