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"
23 #include "funcrequest.h"
25 #include "LaTeXFeatures.h"
28 #include "metricsinfo.h"
29 #include "outputparams.h"
31 #include "frontends/Alert.h"
32 #include "frontends/LyXView.h"
33 #include "frontends/Painter.h"
35 #include "graphics/PreviewImage.h"
36 #include "graphics/PreviewLoader.h"
38 #include "insets/render_preview.h"
40 #include "support/FileInfo.h"
41 #include "support/filename.h"
42 #include "support/filetools.h"
43 #include "support/lstrings.h" // contains
44 #include "support/lyxlib.h"
45 #include "support/tostr.h"
47 #include <boost/bind.hpp>
49 #include "support/std_ostream.h"
50 #include "support/std_sstream.h"
52 using lyx::support::AddName;
53 using lyx::support::AbsolutePath;
54 using lyx::support::bformat;
55 using lyx::support::ChangeExtension;
56 using lyx::support::contains;
57 using lyx::support::copy;
58 using lyx::support::FileInfo;
59 using lyx::support::FileName;
60 using lyx::support::GetFileContents;
61 using lyx::support::IsFileReadable;
62 using lyx::support::IsLyXFilename;
63 using lyx::support::MakeAbsPath;
64 using lyx::support::MakeDisplayPath;
65 using lyx::support::MakeRelPath;
66 using lyx::support::OnlyFilename;
67 using lyx::support::OnlyPath;
68 using lyx::support::subst;
69 using lyx::support::sum;
74 using std::istringstream;
76 using std::ostringstream;
79 extern BufferList bufferlist;
84 string const uniqueID()
86 static unsigned int seed = 1000;
87 return "file" + tostr(++seed);
93 InsetInclude::InsetInclude(InsetCommandParams const & p)
94 : params_(p), include_label(uniqueID()),
95 preview_(new RenderMonitoredPreview(this)),
98 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
102 InsetInclude::InsetInclude(InsetInclude const & other)
104 params_(other.params_),
105 include_label(other.include_label),
106 preview_(new RenderMonitoredPreview(this)),
107 set_label_(other.set_label_)
109 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
113 InsetInclude::~InsetInclude()
115 InsetIncludeMailer(*this).hideDialog();
119 void InsetInclude::priv_dispatch(LCursor & cur, FuncRequest & cmd)
121 switch (cmd.action) {
123 case LFUN_INSET_MODIFY: {
124 InsetCommandParams p;
125 InsetIncludeMailer::string2params(cmd.argument, p);
126 if (!p.getCmdName().empty()) {
127 set(p, cur.buffer());
133 case LFUN_INSET_DIALOG_UPDATE:
134 InsetIncludeMailer(*this).updateDialog(&cur.bv());
137 case LFUN_MOUSE_RELEASE:
138 if (button_.box().contains(cmd.x, cmd.y))
139 InsetIncludeMailer(*this).showDialog(&cur.bv());
142 case LFUN_INSET_DIALOG_SHOW:
143 InsetIncludeMailer(*this).showDialog(&cur.bv());
147 InsetOld::priv_dispatch(cur, cmd);
153 InsetCommandParams const & InsetInclude::params() const
161 /// the type of inclusion
170 Types type(InsetCommandParams const & params)
172 string const command_name = params.getCmdName();
174 if (command_name == "input")
176 if (command_name == "verbatiminput")
178 if (command_name == "verbatiminput*")
184 bool isVerbatim(InsetCommandParams const & params)
186 string const command_name = params.getCmdName();
187 return command_name == "verbatiminput" ||
188 command_name == "verbatiminput*";
192 string const masterFilename(Buffer const & buffer)
194 return buffer.getMasterBuffer()->fileName();
198 string const parentFilename(Buffer const & buffer)
200 return buffer.fileName();
204 string const includedFilename(Buffer const & buffer,
205 InsetCommandParams const & params)
207 return MakeAbsPath(params.getContents(),
208 OnlyPath(parentFilename(buffer)));
212 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
217 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
222 if (preview_->monitoring())
223 preview_->stopMonitoring();
225 if (type(params_) == INPUT)
226 add_preview(*preview_, *this, buffer);
230 auto_ptr<InsetBase> InsetInclude::clone() const
232 return auto_ptr<InsetBase>(new InsetInclude(*this));
236 void InsetInclude::write(Buffer const &, ostream & os) const
242 void InsetInclude::write(ostream & os) const
244 os << "Include " << params_.getCommand() << '\n'
245 << "preview " << tostr(params_.preview()) << '\n';
249 void InsetInclude::read(Buffer const &, LyXLex & lex)
255 void InsetInclude::read(LyXLex & lex)
261 string const InsetInclude::getScreenLabel(Buffer const &) const
265 switch (type(params_)) {
266 case INPUT: temp += _("Input"); break;
267 case VERB: temp += _("Verbatim Input"); break;
268 case VERBAST: temp += _("Verbatim Input*"); break;
269 case INCLUDE: temp += _("Include"); break;
274 if (params_.getContents().empty())
277 temp += OnlyFilename(params_.getContents());
285 /// return true if the file is or got loaded.
286 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
288 if (isVerbatim(params))
291 string const included_file = includedFilename(buffer, params);
292 if (!IsLyXFilename(included_file))
295 Buffer * buf = bufferlist.getBuffer(included_file);
297 // the readonly flag can/will be wrong, not anymore I think.
298 FileInfo finfo(included_file);
301 buf = bufferlist.newBuffer(included_file);
302 if (!loadLyXFile(buf, included_file))
306 buf->setParentName(parentFilename(buffer));
314 int InsetInclude::latex(Buffer const & buffer, ostream & os,
315 OutputParams const & runparams) const
317 string incfile(params_.getContents());
319 // Do nothing if no file name has been specified
323 string const included_file = includedFilename(buffer, params_);
324 Buffer const * const m_buffer = buffer.getMasterBuffer();
326 // if incfile is relative, make it relative to the master
328 if (!AbsolutePath(incfile)) {
329 incfile = MakeRelPath(included_file,
330 m_buffer->filePath());
333 // write it to a file (so far the complete file)
334 string writefile = ChangeExtension(included_file, ".tex");
336 if (!runparams.nice) {
337 incfile = FileName(writefile).mangledFilename();
338 writefile = MakeAbsPath(incfile, m_buffer->temppath());
340 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
341 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
343 if (loadIfNeeded(buffer, params_)) {
344 Buffer * tmp = bufferlist.getBuffer(included_file);
346 if (tmp->params().textclass != m_buffer->params().textclass) {
347 string text = bformat(_("Included file `%1$s'\n"
348 "has textclass `%2$s'\n"
349 "while parent file has textclass `%3$s'."),
350 MakeDisplayPath(included_file),
351 tmp->params().getLyXTextClass().name(),
352 m_buffer->params().getLyXTextClass().name());
353 Alert::warning(_("Different textclasses"), text);
357 tmp->markDepClean(m_buffer->temppath());
360 #warning Second argument is irrelevant!
361 // since only_body is true, makeLaTeXFile will not look at second
362 // argument. Should we set it to string(), or should makeLaTeXFile
363 // make use of it somehow? (JMarc 20031002)
365 tmp->makeLaTeXFile(writefile,
366 OnlyPath(masterFilename(buffer)),
368 } else if (!runparams.nice) {
369 // Copy the file to the temp dir, so that .aux files etc.
370 // are not created in the original dir. Files included by
371 // this file will be found via input@path, see ../buffer.C.
372 unsigned long const checksum_in = sum(included_file);
373 unsigned long const checksum_out = sum(writefile);
375 if (checksum_in != checksum_out) {
376 if (!copy(included_file, writefile)) {
378 << bformat(_("Could not copy the file\n%1$s\n"
379 "into the temporary directory."),
387 if (isVerbatim(params_)) {
388 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
389 } else if (type(params_) == INPUT) {
390 // \input wants file with extension (default is .tex)
391 if (!IsLyXFilename(included_file)) {
392 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
394 os << '\\' << params_.getCmdName() << '{'
395 << ChangeExtension(incfile, ".tex")
399 // \include don't want extension and demands that the
400 // file really have .tex
401 os << '\\' << params_.getCmdName() << '{'
402 << ChangeExtension(incfile, string())
410 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
411 OutputParams const &) const
413 if (isVerbatim(params_))
414 os << GetFileContents(includedFilename(buffer, params_));
419 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
420 OutputParams const & runparams) const
422 string incfile(params_.getContents());
424 // Do nothing if no file name has been specified
428 string const included_file = includedFilename(buffer, params_);
430 if (loadIfNeeded(buffer, params_)) {
431 Buffer * tmp = bufferlist.getBuffer(included_file);
433 // write it to a file (so far the complete file)
434 string writefile = ChangeExtension(included_file, ".sgml");
436 if (!runparams.nice) {
437 incfile = FileName(writefile).mangledFilename();
438 writefile = MakeAbsPath(incfile,
439 buffer.getMasterBuffer()->temppath());
442 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
443 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
445 OutputParams runp = runparams;
446 tmp->makeLinuxDocFile(writefile, runp, true);
449 if (isVerbatim(params_)) {
451 << GetFileContents(included_file)
454 os << '&' << include_label << ';';
460 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
461 OutputParams const & runparams) const
463 string incfile(params_.getContents());
465 // Do nothing if no file name has been specified
469 string const included_file = includedFilename(buffer, params_);
471 if (loadIfNeeded(buffer, params_)) {
472 Buffer * tmp = bufferlist.getBuffer(included_file);
474 // write it to a file (so far the complete file)
475 string writefile = ChangeExtension(included_file, ".sgml");
477 if (!runparams.nice) {
478 incfile = FileName(writefile).mangledFilename();
479 writefile = MakeAbsPath(incfile,
480 buffer.getMasterBuffer()->temppath());
483 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
484 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
486 OutputParams runp = runparams;
487 tmp->makeDocBookFile(writefile, runp, true);
490 if (isVerbatim(params_)) {
491 os << "<inlinegraphic fileref=\""
492 << '&' << include_label << ';'
493 << "\" format=\"linespecific\">";
495 os << '&' << include_label << ';';
501 void InsetInclude::validate(LaTeXFeatures & features) const
503 string incfile(params_.getContents());
506 Buffer const & buffer = features.buffer();
508 string const included_file = includedFilename(buffer, params_);
510 if (IsLyXFilename(included_file))
511 writefile = ChangeExtension(included_file, ".sgml");
513 writefile = included_file;
515 if (!features.nice() && !isVerbatim(params_)) {
516 incfile = FileName(writefile).mangledFilename();
517 writefile = MakeAbsPath(incfile,
518 buffer.getMasterBuffer()->temppath());
521 features.includeFile(include_label, writefile);
523 if (isVerbatim(params_))
524 features.require("verbatim");
526 // Here we must do the fun stuff...
527 // Load the file in the include if it needs
529 if (loadIfNeeded(buffer, params_)) {
531 Buffer * const tmp = bufferlist.getBuffer(included_file);
533 // We must temporarily change features.buffer,
534 // otherwise it would always be the master buffer,
535 // and nested includes would not work.
536 features.setBuffer(*tmp);
537 tmp->validate(features);
538 features.setBuffer(buffer);
544 void InsetInclude::getLabelList(Buffer const & buffer,
545 std::vector<string> & list) const
547 if (loadIfNeeded(buffer, params_)) {
548 string const included_file = includedFilename(buffer, params_);
549 Buffer * tmp = bufferlist.getBuffer(included_file);
550 tmp->setParentName("");
551 tmp->getLabelList(list);
552 tmp->setParentName(parentFilename(buffer));
557 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
558 std::vector<std::pair<string,string> > & keys) const
560 if (loadIfNeeded(buffer, params_)) {
561 string const included_file = includedFilename(buffer, params_);
562 Buffer * tmp = bufferlist.getBuffer(included_file);
563 tmp->setParentName("");
564 tmp->fillWithBibKeys(keys);
565 tmp->setParentName(parentFilename(buffer));
570 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
572 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
574 bool use_preview = false;
575 if (RenderPreview::activated()) {
576 lyx::graphics::PreviewImage const * pimage =
577 preview_->getPreviewImage(*mi.base.bv->buffer());
578 use_preview = pimage && pimage->image();
582 preview_->metrics(mi, dim);
586 button_.update(getScreenLabel(*mi.base.bv->buffer()),
587 editable() != NOT_EDITABLE);
589 button_.metrics(mi, dim);
591 int center_indent = type(params_) == INPUT ?
592 0 : (mi.base.textwidth - dim.wid) / 2;
593 Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
596 dim.wid = mi.base.textwidth;
601 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
603 setPosCache(pi, x, y);
605 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
607 bool use_preview = false;
608 if (RenderPreview::activated()) {
609 lyx::graphics::PreviewImage const * pimage =
610 preview_->getPreviewImage(*pi.base.bv->buffer());
611 use_preview = pimage && pimage->image();
615 preview_->draw(pi, x + button_.box().x1, y);
617 button_.draw(pi, x + button_.box().x1, y);
625 void InsetInclude::fileChanged() const
627 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
631 Buffer const & buffer = *buffer_ptr;
632 preview_->removePreview(buffer);
633 add_preview(*preview_.get(), *this, buffer);
634 preview_->startLoading(buffer);
640 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
642 string const included_file = includedFilename(buffer, params);
644 return type(params) == INPUT && params.preview() &&
645 IsFileReadable(included_file);
649 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
652 OutputParams runparams;
653 runparams.flavor = OutputParams::LATEX;
654 inset.latex(buffer, os, runparams);
660 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
661 Buffer const & buffer)
663 InsetCommandParams const & params = inset.params();
664 if (RenderPreview::activated() && preview_wanted(params, buffer)) {
665 renderer.setAbsFile(includedFilename(buffer, params));
666 string const snippet = latex_string(inset, buffer);
667 renderer.addPreview(snippet, buffer);
674 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
676 Buffer const & buffer = ploader.buffer();
677 if (preview_wanted(params(), buffer)) {
678 preview_->setAbsFile(includedFilename(buffer, params()));
679 string const snippet = latex_string(*this, buffer);
680 preview_->addPreview(snippet, ploader);
685 string const InsetIncludeMailer::name_("include");
687 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
692 string const InsetIncludeMailer::inset2string(Buffer const &) const
694 return params2string(inset_.params());
698 void InsetIncludeMailer::string2params(string const & in,
699 InsetCommandParams & params)
701 params = InsetCommandParams();
705 istringstream data(in);
711 if (!lex || name != name_)
712 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
714 // This is part of the inset proper that is usually swallowed
715 // by LyXText::readInset
718 if (!lex || id != "Include")
719 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
721 InsetInclude inset(params);
723 params = inset.params();
728 InsetIncludeMailer::params2string(InsetCommandParams const & params)
730 InsetInclude inset(params);
732 data << name_ << ' ';
734 data << "\\end_inset\n";