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"
29 #include "metricsinfo.h"
30 #include "outputparams.h"
32 #include "frontends/Alert.h"
33 #include "frontends/LyXView.h"
34 #include "frontends/Painter.h"
36 #include "graphics/PreviewImage.h"
37 #include "graphics/PreviewLoader.h"
39 #include "insets/render_preview.h"
41 #include "support/FileInfo.h"
42 #include "support/filename.h"
43 #include "support/filetools.h"
44 #include "support/lstrings.h" // contains
45 #include "support/lyxlib.h"
46 #include "support/tostr.h"
48 #include <boost/bind.hpp>
50 #include "support/std_ostream.h"
51 #include "support/std_sstream.h"
53 using lyx::support::AddName;
54 using lyx::support::AbsolutePath;
55 using lyx::support::bformat;
56 using lyx::support::ChangeExtension;
57 using lyx::support::contains;
58 using lyx::support::copy;
59 using lyx::support::FileInfo;
60 using lyx::support::FileName;
61 using lyx::support::GetFileContents;
62 using lyx::support::IsFileReadable;
63 using lyx::support::IsLyXFilename;
64 using lyx::support::MakeAbsPath;
65 using lyx::support::MakeDisplayPath;
66 using lyx::support::MakeRelPath;
67 using lyx::support::OnlyFilename;
68 using lyx::support::OnlyPath;
69 using lyx::support::subst;
70 using lyx::support::sum;
75 using std::istringstream;
77 using std::ostringstream;
80 extern BufferList bufferlist;
85 string const uniqueID()
87 static unsigned int seed = 1000;
88 return "file" + tostr(++seed);
94 InsetInclude::InsetInclude(InsetCommandParams const & p)
95 : params_(p), include_label(uniqueID()),
96 preview_(new RenderMonitoredPreview(this)),
99 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
103 InsetInclude::InsetInclude(InsetInclude const & other)
105 params_(other.params_),
106 include_label(other.include_label),
107 preview_(new RenderMonitoredPreview(this)),
108 set_label_(other.set_label_)
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.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 BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
575 bool use_preview = false;
576 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
577 lyx::graphics::PreviewImage const * pimage =
578 preview_->getPreviewImage(*mi.base.bv->buffer());
579 use_preview = pimage && pimage->image();
583 preview_->metrics(mi, dim);
587 button_.update(getScreenLabel(*mi.base.bv->buffer()),
588 editable() != NOT_EDITABLE);
590 button_.metrics(mi, dim);
592 int center_indent = type(params_) == INPUT ?
593 0 : (mi.base.textwidth - dim.wid) / 2;
594 Box b(center_indent, center_indent + dim.wid, -dim.asc, dim.des);
597 dim.wid = mi.base.textwidth;
602 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
604 setPosCache(pi, x, y);
606 BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
608 bool use_preview = false;
609 if (RenderPreview::status() == LyXRC::PREVIEW_OFF) {
610 lyx::graphics::PreviewImage const * pimage =
611 preview_->getPreviewImage(*pi.base.bv->buffer());
612 use_preview = pimage && pimage->image();
616 preview_->draw(pi, x + button_.box().x1, y);
618 button_.draw(pi, x + button_.box().x1, y);
626 void InsetInclude::fileChanged() const
628 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
632 Buffer const & buffer = *buffer_ptr;
633 preview_->removePreview(buffer);
634 add_preview(*preview_.get(), *this, buffer);
635 preview_->startLoading(buffer);
641 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
643 string const included_file = includedFilename(buffer, params);
645 return type(params) == INPUT && params.preview() &&
646 IsFileReadable(included_file);
650 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
653 OutputParams runparams;
654 runparams.flavor = OutputParams::LATEX;
655 inset.latex(buffer, os, runparams);
661 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
662 Buffer const & buffer)
664 InsetCommandParams const & params = inset.params();
665 if (RenderPreview::status() == LyXRC::PREVIEW_OFF &&
666 preview_wanted(params, buffer)) {
667 renderer.setAbsFile(includedFilename(buffer, params));
668 string const snippet = latex_string(inset, buffer);
669 renderer.addPreview(snippet, buffer);
676 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
678 Buffer const & buffer = ploader.buffer();
679 if (preview_wanted(params(), buffer)) {
680 preview_->setAbsFile(includedFilename(buffer, params()));
681 string const snippet = latex_string(*this, buffer);
682 preview_->addPreview(snippet, ploader);
687 string const InsetIncludeMailer::name_("include");
689 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
694 string const InsetIncludeMailer::inset2string(Buffer const &) const
696 return params2string(inset_.params());
700 void InsetIncludeMailer::string2params(string const & in,
701 InsetCommandParams & params)
703 params = InsetCommandParams();
707 istringstream data(in);
713 if (!lex || name != name_)
714 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
716 // This is part of the inset proper that is usually swallowed
717 // by LyXText::readInset
720 if (!lex || id != "Include")
721 return print_mailer_error("InsetBoxMailer", in, 2, "Include");
723 InsetInclude inset(params);
725 params = inset.params();
730 InsetIncludeMailer::params2string(InsetCommandParams const & params)
732 InsetInclude inset(params);
734 data << name_ << ' ';
736 data << "\\end_inset\n";