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/PreviewLoader.h"
37 #include "insets/render_preview.h"
39 #include "support/FileInfo.h"
40 #include "support/filename.h"
41 #include "support/filetools.h"
42 #include "support/lstrings.h" // contains
43 #include "support/lyxlib.h"
44 #include "support/tostr.h"
46 #include <boost/bind.hpp>
48 #include "support/std_ostream.h"
49 #include "support/std_sstream.h"
51 using lyx::support::AddName;
52 using lyx::support::AbsolutePath;
53 using lyx::support::bformat;
54 using lyx::support::ChangeExtension;
55 using lyx::support::contains;
56 using lyx::support::copy;
57 using lyx::support::FileInfo;
58 using lyx::support::FileName;
59 using lyx::support::GetFileContents;
60 using lyx::support::IsFileReadable;
61 using lyx::support::IsLyXFilename;
62 using lyx::support::MakeAbsPath;
63 using lyx::support::MakeDisplayPath;
64 using lyx::support::MakeRelPath;
65 using lyx::support::OnlyFilename;
66 using lyx::support::OnlyPath;
67 using lyx::support::subst;
68 using lyx::support::sum;
73 using std::istringstream;
75 using std::ostringstream;
78 extern BufferList bufferlist;
83 string const uniqueID()
85 static unsigned int seed = 1000;
86 return "file" + tostr(++seed);
92 InsetInclude::InsetInclude(InsetCommandParams const & p)
93 : params_(p), include_label(uniqueID()),
94 preview_(new RenderMonitoredPreview),
97 preview_->connect(boost::bind(&InsetInclude::statusChanged, 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),
107 set_label_(other.set_label_)
109 preview_->connect(boost::bind(&InsetInclude::statusChanged, this));
110 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
114 InsetInclude::~InsetInclude()
116 InsetIncludeMailer(*this).hideDialog();
120 void InsetInclude::priv_dispatch(LCursor & cur, FuncRequest & cmd)
122 switch (cmd.action) {
124 case LFUN_INSET_MODIFY: {
125 InsetCommandParams p;
126 InsetIncludeMailer::string2params(cmd.argument, p);
127 if (!p.getCmdName().empty()) {
128 set(p, *cur.bv().buffer());
134 case LFUN_INSET_DIALOG_UPDATE:
135 InsetIncludeMailer(*this).updateDialog(&cur.bv());
138 case LFUN_MOUSE_RELEASE:
139 if (button_.box().contains(cmd.x, cmd.y))
140 InsetIncludeMailer(*this).showDialog(&cur.bv());
143 case LFUN_INSET_DIALOG_SHOW:
144 InsetIncludeMailer(*this).showDialog(&cur.bv());
148 InsetOld::priv_dispatch(cur, cmd);
154 InsetCommandParams const & InsetInclude::params() const
162 /// the type of inclusion
171 Types type(InsetCommandParams const & params)
173 string const command_name = params.getCmdName();
175 if (command_name == "input")
177 if (command_name == "verbatiminput")
179 if (command_name == "verbatiminput*")
185 bool isVerbatim(InsetCommandParams const & params)
187 string const command_name = params.getCmdName();
188 return command_name == "verbatiminput" ||
189 command_name == "verbatiminput*";
193 string const masterFilename(Buffer const & buffer)
195 return buffer.getMasterBuffer()->fileName();
199 string const parentFilename(Buffer const & buffer)
201 return buffer.fileName();
205 string const includedFilename(Buffer const & buffer,
206 InsetCommandParams const & params)
208 return MakeAbsPath(params.getContents(),
209 OnlyPath(parentFilename(buffer)));
213 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
218 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
223 if (preview_->monitoring())
224 preview_->stopMonitoring();
226 if (type(params_) == INPUT)
227 add_preview(*preview_, *this, buffer);
231 auto_ptr<InsetBase> InsetInclude::clone() const
233 return auto_ptr<InsetBase>(new InsetInclude(*this));
237 void InsetInclude::write(Buffer const &, ostream & os) const
243 void InsetInclude::write(ostream & os) const
245 os << "Include " << params_.getCommand() << '\n'
246 << "preview " << tostr(params_.preview()) << '\n';
250 void InsetInclude::read(Buffer const &, LyXLex & lex)
256 void InsetInclude::read(LyXLex & lex)
262 string const InsetInclude::getScreenLabel(Buffer const &) const
266 switch (type(params_)) {
267 case INPUT: temp += _("Input"); break;
268 case VERB: temp += _("Verbatim Input"); break;
269 case VERBAST: temp += _("Verbatim Input*"); break;
270 case INCLUDE: temp += _("Include"); break;
275 if (params_.getContents().empty())
278 temp += OnlyFilename(params_.getContents());
286 /// return true if the file is or got loaded.
287 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
289 if (isVerbatim(params))
292 string const included_file = includedFilename(buffer, params);
293 if (!IsLyXFilename(included_file))
296 Buffer * buf = bufferlist.getBuffer(included_file);
298 // the readonly flag can/will be wrong, not anymore I think.
299 FileInfo finfo(included_file);
302 buf = bufferlist.newBuffer(included_file);
303 if (!loadLyXFile(buf, included_file))
307 buf->setParentName(parentFilename(buffer));
315 int InsetInclude::latex(Buffer const & buffer, ostream & os,
316 OutputParams const & runparams) const
318 string incfile(params_.getContents());
320 // Do nothing if no file name has been specified
324 string const included_file = includedFilename(buffer, params_);
325 Buffer const * const m_buffer = buffer.getMasterBuffer();
327 // if incfile is relative, make it relative to the master
329 if (!AbsolutePath(incfile)) {
330 incfile = MakeRelPath(included_file,
331 m_buffer->filePath());
334 // write it to a file (so far the complete file)
335 string writefile = ChangeExtension(included_file, ".tex");
337 if (!runparams.nice) {
338 incfile = FileName(writefile).mangledFilename();
339 writefile = MakeAbsPath(incfile, m_buffer->temppath());
341 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
342 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
344 if (loadIfNeeded(buffer, params_)) {
345 Buffer * tmp = bufferlist.getBuffer(included_file);
347 if (tmp->params().textclass != m_buffer->params().textclass) {
348 string text = bformat(_("Included file `%1$s'\n"
349 "has textclass `%2$s'\n"
350 "while parent file has textclass `%3$s'."),
351 MakeDisplayPath(included_file),
352 tmp->params().getLyXTextClass().name(),
353 m_buffer->params().getLyXTextClass().name());
354 Alert::warning(_("Different textclasses"), text);
358 tmp->markDepClean(m_buffer->temppath());
361 #warning Second argument is irrelevant!
362 // since only_body is true, makeLaTeXFile will not look at second
363 // argument. Should we set it to string(), or should makeLaTeXFile
364 // make use of it somehow? (JMarc 20031002)
366 tmp->makeLaTeXFile(writefile,
367 OnlyPath(masterFilename(buffer)),
369 } else if (!runparams.nice) {
370 // Copy the file to the temp dir, so that .aux files etc.
371 // are not created in the original dir. Files included by
372 // this file will be found via input@path, see ../buffer.C.
373 unsigned long const checksum_in = sum(included_file);
374 unsigned long const checksum_out = sum(writefile);
376 if (checksum_in != checksum_out) {
377 if (!copy(included_file, writefile)) {
379 << bformat(_("Could not copy the file\n%1$s\n"
380 "into the temporary directory."),
388 if (isVerbatim(params_)) {
389 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
390 } else if (type(params_) == INPUT) {
391 // \input wants file with extension (default is .tex)
392 if (!IsLyXFilename(included_file)) {
393 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
395 os << '\\' << params_.getCmdName() << '{'
396 << ChangeExtension(incfile, ".tex")
400 // \include don't want extension and demands that the
401 // file really have .tex
402 os << '\\' << params_.getCmdName() << '{'
403 << ChangeExtension(incfile, string())
411 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
412 OutputParams const &) const
414 if (isVerbatim(params_))
415 os << GetFileContents(includedFilename(buffer, params_));
420 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
421 OutputParams const & runparams) const
423 string incfile(params_.getContents());
425 // Do nothing if no file name has been specified
429 string const included_file = includedFilename(buffer, params_);
431 if (loadIfNeeded(buffer, params_)) {
432 Buffer * tmp = bufferlist.getBuffer(included_file);
434 // write it to a file (so far the complete file)
435 string writefile = ChangeExtension(included_file, ".sgml");
437 if (!runparams.nice) {
438 incfile = FileName(writefile).mangledFilename();
439 writefile = MakeAbsPath(incfile,
440 buffer.getMasterBuffer()->temppath());
443 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
444 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
446 OutputParams runp = runparams;
447 tmp->makeLinuxDocFile(writefile, runp, true);
450 if (isVerbatim(params_)) {
452 << GetFileContents(included_file)
455 os << '&' << include_label << ';';
461 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
462 OutputParams const & runparams) const
464 string incfile(params_.getContents());
466 // Do nothing if no file name has been specified
470 string const included_file = includedFilename(buffer, params_);
472 if (loadIfNeeded(buffer, params_)) {
473 Buffer * tmp = bufferlist.getBuffer(included_file);
475 // write it to a file (so far the complete file)
476 string writefile = ChangeExtension(included_file, ".sgml");
478 if (!runparams.nice) {
479 incfile = FileName(writefile).mangledFilename();
480 writefile = MakeAbsPath(incfile,
481 buffer.getMasterBuffer()->temppath());
484 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
485 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
487 OutputParams runp = runparams;
488 tmp->makeDocBookFile(writefile, runp, true);
491 if (isVerbatim(params_)) {
492 os << "<inlinegraphic fileref=\""
493 << '&' << include_label << ';'
494 << "\" format=\"linespecific\">";
496 os << '&' << include_label << ';';
502 void InsetInclude::validate(LaTeXFeatures & features) const
504 string incfile(params_.getContents());
507 Buffer const & buffer = features.buffer();
509 string const included_file = includedFilename(buffer, params_);
511 if (IsLyXFilename(included_file))
512 writefile = ChangeExtension(included_file, ".sgml");
514 writefile = included_file;
516 if (!features.nice() && !isVerbatim(params_)) {
517 incfile = FileName(writefile).mangledFilename();
518 writefile = MakeAbsPath(incfile,
519 buffer.getMasterBuffer()->temppath());
522 features.includeFile(include_label, writefile);
524 if (isVerbatim(params_))
525 features.require("verbatim");
527 // Here we must do the fun stuff...
528 // Load the file in the include if it needs
530 if (loadIfNeeded(buffer, params_)) {
532 Buffer * const tmp = bufferlist.getBuffer(included_file);
534 // We must temporarily change features.buffer,
535 // otherwise it would always be the master buffer,
536 // and nested includes would not work.
537 features.setBuffer(*tmp);
538 tmp->validate(features);
539 features.setBuffer(buffer);
545 void InsetInclude::getLabelList(Buffer const & buffer,
546 std::vector<string> & list) const
548 if (loadIfNeeded(buffer, params_)) {
549 string const included_file = includedFilename(buffer, params_);
550 Buffer * tmp = bufferlist.getBuffer(included_file);
551 tmp->setParentName("");
552 tmp->getLabelList(list);
553 tmp->setParentName(parentFilename(buffer));
558 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
559 std::vector<std::pair<string,string> > & keys) const
561 if (loadIfNeeded(buffer, params_)) {
562 string const included_file = includedFilename(buffer, params_);
563 Buffer * tmp = bufferlist.getBuffer(included_file);
564 tmp->setParentName("");
565 tmp->fillWithBibKeys(keys);
566 tmp->setParentName(parentFilename(buffer));
571 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
573 if (RenderPreview::activated() && preview_->previewReady()) {
574 preview_->metrics(mi, dim);
578 button_.update(getScreenLabel(*mi.base.bv->buffer()),
579 editable() != NOT_EDITABLE);
581 button_.metrics(mi, dim);
583 int center_indent = type(params_) == INPUT ?
584 0 : (mi.base.textwidth - dim.wid) / 2;
585 Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
588 dim.wid = mi.base.textwidth;
593 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
595 setPosCache(pi, x, y);
597 if (!RenderPreview::activated() || !preview_->previewReady()) {
598 button_.draw(pi, x + button_.box().x1, y);
602 preview_->draw(pi, x + button_.box().x1, y);
610 void InsetInclude::statusChanged() const
612 LyX::cref().updateInset(this);
616 void InsetInclude::fileChanged() const
618 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
622 Buffer const & buffer = *buffer_ptr;
623 preview_->removePreview(buffer);
624 add_preview(*preview_.get(), *this, buffer);
625 preview_->startLoading(buffer);
631 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
633 string const included_file = includedFilename(buffer, params);
635 return type(params) == INPUT && params.preview() &&
636 IsFileReadable(included_file);
640 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
643 OutputParams runparams;
644 runparams.flavor = OutputParams::LATEX;
645 inset.latex(buffer, os, runparams);
651 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
652 Buffer const & buffer)
654 InsetCommandParams const & params = inset.params();
655 if (RenderPreview::activated() && preview_wanted(params, buffer)) {
656 renderer.setAbsFile(includedFilename(buffer, params));
657 string const snippet = latex_string(inset, buffer);
658 renderer.addPreview(snippet, buffer);
665 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
667 Buffer const & buffer = ploader.buffer();
668 if (preview_wanted(params(), buffer)) {
669 preview_->setAbsFile(includedFilename(buffer, params()));
670 string const snippet = latex_string(*this, buffer);
671 preview_->addPreview(snippet, ploader);
676 string const InsetIncludeMailer::name_("include");
678 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
683 string const InsetIncludeMailer::inset2string(Buffer const &) const
685 return params2string(inset_.params());
689 void InsetIncludeMailer::string2params(string const & in,
690 InsetCommandParams & params)
692 params = InsetCommandParams();
696 istringstream data(in);
702 if (!lex || name != name_)
703 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
705 // This is part of the inset proper that is usually swallowed
706 // by LyXText::readInset
709 if (!lex || id != "Include")
710 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
712 InsetInclude inset(params);
714 params = inset.params();
719 InsetIncludeMailer::params2string(InsetCommandParams const & params)
721 InsetInclude inset(params);
723 data << name_ << ' ';
725 data << "\\end_inset\n";