]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
ea9c3f60288b55c7cfc4dbe62efc6964cda8aaeb
[lyx.git] / src / insets / insetinclude.C
1 /**
2  * \file insetinclude.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insetinclude.h"
14
15 #include "buffer.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "BufferView.h"
20 #include "cursor.h"
21 #include "debug.h"
22 #include "dispatchresult.h"
23 #include "exporter.h"
24 #include "funcrequest.h"
25 #include "FuncStatus.h"
26 #include "gettext.h"
27 #include "LaTeXFeatures.h"
28 #include "lyx_main.h"
29 #include "lyxrc.h"
30 #include "lyxlex.h"
31 #include "metricsinfo.h"
32 #include "outputparams.h"
33
34 #include "frontends/Alert.h"
35 #include "frontends/LyXView.h"
36 #include "frontends/Painter.h"
37
38 #include "graphics/PreviewImage.h"
39 #include "graphics/PreviewLoader.h"
40
41 #include "insets/render_preview.h"
42
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"
48
49 #include <boost/bind.hpp>
50 #include <boost/filesystem/operations.hpp>
51
52 #include "support/std_ostream.h"
53
54 #include <sstream>
55
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;
74
75 using std::endl;
76 using std::string;
77 using std::auto_ptr;
78 using std::istringstream;
79 using std::ostream;
80 using std::ostringstream;
81
82 namespace fs = boost::filesystem;
83
84 extern BufferList bufferlist;
85
86
87 namespace {
88
89 string const uniqueID()
90 {
91         static unsigned int seed = 1000;
92         return "file" + convert<string>(++seed);
93 }
94
95 } // namespace anon
96
97
98 InsetInclude::InsetInclude(InsetCommandParams const & p)
99         : params_(p), include_label(uniqueID()),
100           preview_(new RenderMonitoredPreview(this)),
101           set_label_(false)
102 {
103         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
104 }
105
106
107 InsetInclude::InsetInclude(InsetInclude const & other)
108         : InsetOld(other),
109           params_(other.params_),
110           include_label(other.include_label),
111           preview_(new RenderMonitoredPreview(this)),
112           set_label_(false)
113 {
114         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
115 }
116
117
118 InsetInclude::~InsetInclude()
119 {
120         InsetIncludeMailer(*this).hideDialog();
121 }
122
123
124 void InsetInclude::doDispatch(LCursor & cur, FuncRequest & cmd)
125 {
126         switch (cmd.action) {
127
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                 else
134                         cur.noUpdate();
135                 break;
136         }
137
138         case LFUN_INSET_DIALOG_UPDATE:
139                 InsetIncludeMailer(*this).updateDialog(&cur.bv());
140                 break;
141
142         case LFUN_MOUSE_RELEASE:
143         case LFUN_INSET_DIALOG_SHOW:
144                 InsetIncludeMailer(*this).showDialog(&cur.bv());
145                 break;
146
147         default:
148                 InsetBase::doDispatch(cur, cmd);
149                 break;
150         }
151 }
152
153
154 bool InsetInclude::getStatus(LCursor & cur, FuncRequest const & cmd,
155                 FuncStatus & flag) const
156 {
157         switch (cmd.action) {
158
159         case LFUN_INSET_MODIFY:
160         case LFUN_INSET_DIALOG_UPDATE:
161         case LFUN_INSET_DIALOG_SHOW:
162                 flag.enabled(true);
163                 return true;
164
165         default:
166                 return InsetBase::getStatus(cur, cmd, flag);
167         }
168 }
169
170
171 InsetCommandParams const & InsetInclude::params() const
172 {
173         return params_;
174 }
175
176
177 namespace {
178
179 /// the type of inclusion
180 enum Types {
181         INCLUDE = 0,
182         VERB = 1,
183         INPUT = 2,
184         VERBAST = 3
185 };
186
187
188 Types type(InsetCommandParams const & params)
189 {
190         string const command_name = params.getCmdName();
191
192         if (command_name == "input")
193                 return INPUT;
194         if  (command_name == "verbatiminput")
195                 return VERB;
196         if  (command_name == "verbatiminput*")
197                 return VERBAST;
198         return INCLUDE;
199 }
200
201
202 bool isVerbatim(InsetCommandParams const & params)
203 {
204         string const command_name = params.getCmdName();
205         return command_name == "verbatiminput" ||
206                 command_name == "verbatiminput*";
207 }
208
209
210 string const masterFilename(Buffer const & buffer)
211 {
212         return buffer.getMasterBuffer()->fileName();
213 }
214
215
216 string const parentFilename(Buffer const & buffer)
217 {
218         return buffer.fileName();
219 }
220
221
222 string const includedFilename(Buffer const & buffer,
223                               InsetCommandParams const & params)
224 {
225         return MakeAbsPath(params.getContents(),
226                            OnlyPath(parentFilename(buffer)));
227 }
228
229
230 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
231
232 } // namespace anon
233
234
235 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
236 {
237         params_ = p;
238         set_label_ = false;
239
240         if (preview_->monitoring())
241                 preview_->stopMonitoring();
242
243         if (type(params_) == INPUT)
244                 add_preview(*preview_, *this, buffer);
245 }
246
247
248 auto_ptr<InsetBase> InsetInclude::doClone() const
249 {
250         return auto_ptr<InsetBase>(new InsetInclude(*this));
251 }
252
253
254 void InsetInclude::write(Buffer const &, ostream & os) const
255 {
256         write(os);
257 }
258
259
260 void InsetInclude::write(ostream & os) const
261 {
262         os << "Include " << params_.getCommand() << '\n'
263            << "preview " << convert<string>(params_.preview()) << '\n';
264 }
265
266
267 void InsetInclude::read(Buffer const &, LyXLex & lex)
268 {
269         read(lex);
270 }
271
272
273 void InsetInclude::read(LyXLex & lex)
274 {
275         params_.read(lex);
276 }
277
278
279 string const InsetInclude::getScreenLabel(Buffer const &) const
280 {
281         string temp;
282
283         switch (type(params_)) {
284                 case INPUT: temp += _("Input"); break;
285                 case VERB: temp += _("Verbatim Input"); break;
286                 case VERBAST: temp += _("Verbatim Input*"); break;
287                 case INCLUDE: temp += _("Include"); break;
288         }
289
290         temp += ": ";
291
292         if (params_.getContents().empty())
293                 temp += "???";
294         else
295                 temp += OnlyFilename(params_.getContents());
296
297         return temp;
298 }
299
300
301 namespace {
302
303 /// return true if the file is or got loaded.
304 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
305 {
306         if (isVerbatim(params))
307                 return false;
308
309         string const included_file = includedFilename(buffer, params);
310         if (!IsLyXFilename(included_file))
311                 return false;
312
313         Buffer * buf = bufferlist.getBuffer(included_file);
314         if (!buf) {
315                 // the readonly flag can/will be wrong, not anymore I think.
316                 if (!fs::exists(included_file))
317                         return false;
318                 buf = bufferlist.newBuffer(included_file);
319                 if (!loadLyXFile(buf, included_file))
320                         return false;
321         }
322         if (buf)
323                 buf->setParentName(parentFilename(buffer));
324         return buf != 0;
325 }
326
327
328 } // namespace anon
329
330
331 int InsetInclude::latex(Buffer const & buffer, ostream & os,
332                         OutputParams const & runparams) const
333 {
334         string incfile(params_.getContents());
335
336         // Do nothing if no file name has been specified
337         if (incfile.empty())
338                 return 0;
339
340         string const included_file = includedFilename(buffer, params_);
341         Buffer const * const m_buffer = buffer.getMasterBuffer();
342
343         // if incfile is relative, make it relative to the master
344         // buffer directory.
345         if (!AbsolutePath(incfile)) {
346                 incfile = MakeRelPath(included_file,
347                                       m_buffer->filePath());
348         }
349
350         // write it to a file (so far the complete file)
351         string const exportfile = ChangeExtension(incfile, ".tex");
352         string const mangled = FileName(ChangeExtension(included_file,
353                                                         ".tex")).mangledFilename();
354         string const writefile = MakeAbsPath(mangled, m_buffer->temppath());
355
356         if (!runparams.nice)
357                 incfile = mangled;
358         lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
359         lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
360         lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
361
362         if (runparams.inComment)
363                 // Don't try to load or copy the file
364                 ;
365         else if (loadIfNeeded(buffer, params_)) {
366                 Buffer * tmp = bufferlist.getBuffer(included_file);
367
368                 if (tmp->params().textclass != m_buffer->params().textclass) {
369                         string text = bformat(_("Included file `%1$s'\n"
370                                                 "has textclass `%2$s'\n"
371                                                 "while parent file has textclass `%3$s'."),
372                                               MakeDisplayPath(included_file),
373                                               tmp->params().getLyXTextClass().name(),
374                                               m_buffer->params().getLyXTextClass().name());
375                         Alert::warning(_("Different textclasses"), text);
376                         //return 0;
377                 }
378
379                 tmp->markDepClean(m_buffer->temppath());
380
381 #ifdef WITH_WARNINGS
382 #warning handle non existing files
383 #warning Second argument is irrelevant!
384 // since only_body is true, makeLaTeXFile will not look at second
385 // argument. Should we set it to string(), or should makeLaTeXFile
386 // make use of it somehow? (JMarc 20031002)
387 #endif
388                 tmp->makeLaTeXFile(writefile,
389                                    OnlyPath(masterFilename(buffer)),
390                                    runparams, false);
391         } else {
392                 // Copy the file to the temp dir, so that .aux files etc.
393                 // are not created in the original dir. Files included by
394                 // this file will be found via input@path, see ../buffer.C.
395                 unsigned long const checksum_in  = sum(included_file);
396                 unsigned long const checksum_out = sum(writefile);
397
398                 if (checksum_in != checksum_out) {
399                         if (!copy(included_file, writefile)) {
400                                 lyxerr[Debug::LATEX]
401                                         << bformat(_("Could not copy the file\n%1$s\n"
402                                                      "into the temporary directory."),
403                                                    included_file)
404                                         << endl;
405                                 return 0;
406                         }
407                 }
408         }
409
410         if (isVerbatim(params_)) {
411                 incfile = latex_path(incfile);
412                 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
413         } else if (type(params_) == INPUT) {
414                 runparams.exportdata->addExternalFile("latex", writefile,
415                                                       exportfile);
416
417                 // \input wants file with extension (default is .tex)
418                 if (!IsLyXFilename(included_file)) {
419                         incfile = latex_path(incfile);
420                         os << '\\' << params_.getCmdName() << '{' << incfile << '}';
421                 } else {
422                 incfile = ChangeExtension(incfile, ".tex");
423                 incfile = latex_path(incfile);
424                         os << '\\' << params_.getCmdName() << '{'
425                            << incfile
426                            <<  '}';
427                 }
428         } else {
429                 runparams.exportdata->addExternalFile("latex", writefile,
430                                                       exportfile);
431
432                 // \include don't want extension and demands that the
433                 // file really have .tex
434                 incfile = ChangeExtension(incfile, string());
435                 incfile = latex_path(incfile);
436                 os << '\\' << params_.getCmdName() << '{'
437                    << incfile
438                    << '}';
439         }
440
441         return 0;
442 }
443
444
445 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
446                         OutputParams const &) const
447 {
448         if (isVerbatim(params_))
449                 os << GetFileContents(includedFilename(buffer, params_));
450         return 0;
451 }
452
453
454 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
455                            OutputParams const & runparams) const
456 {
457         string incfile(params_.getContents());
458
459         // Do nothing if no file name has been specified
460         if (incfile.empty())
461                 return 0;
462
463         string const included_file = includedFilename(buffer, params_);
464
465         // write it to a file (so far the complete file)
466         string const exportfile = ChangeExtension(incfile, ".sgml");
467         string writefile = ChangeExtension(included_file, ".sgml");
468
469         if (loadIfNeeded(buffer, params_)) {
470                 Buffer * tmp = bufferlist.getBuffer(included_file);
471
472                 writefile = MakeAbsPath(FileName(writefile).mangledFilename(),
473                                         buffer.getMasterBuffer()->temppath());
474                 if (!runparams.nice)
475                         incfile = writefile;
476
477                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
478                 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
479                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
480
481                 tmp->makeLinuxDocFile(writefile, runparams, true);
482         }
483
484         if (isVerbatim(params_)) {
485                 os << "<![CDATA["
486                    << GetFileContents(included_file)
487                    << "]]>";
488         } else {
489                 runparams.exportdata->addExternalFile("linuxdoc", writefile,
490                                                       exportfile);
491                 os << '&' << include_label << ';';
492         }
493
494         return 0;
495 }
496
497
498 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
499                           OutputParams const & runparams) const
500 {
501         string incfile(params_.getContents());
502
503         // Do nothing if no file name has been specified
504         if (incfile.empty())
505                 return 0;
506
507         string const included_file = includedFilename(buffer, params_);
508
509         // write it to a file (so far the complete file)
510         string const exportfile = ChangeExtension(incfile, ".sgml");
511         string writefile = ChangeExtension(included_file, ".sgml");
512
513         if (loadIfNeeded(buffer, params_)) {
514                 Buffer * tmp = bufferlist.getBuffer(included_file);
515
516                 string const mangled = FileName(writefile).mangledFilename();
517                 writefile = MakeAbsPath(mangled,
518                                         buffer.getMasterBuffer()->temppath());
519                 if (!runparams.nice)
520                         incfile = mangled;
521
522                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
523                 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
524                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
525
526                 tmp->makeDocBookFile(writefile, runparams, true);
527         }
528
529         runparams.exportdata->addExternalFile("docbook", writefile,
530                                               exportfile);
531         runparams.exportdata->addExternalFile("docbook-xml", writefile,
532                                               exportfile);
533
534         if (isVerbatim(params_)) {
535                 os << "<inlinegraphic fileref=\""
536                    << '&' << include_label << ';'
537                    << "\" format=\"linespecific\">";
538         } else
539                 os << '&' << include_label << ';';
540
541         return 0;
542 }
543
544
545 void InsetInclude::validate(LaTeXFeatures & features) const
546 {
547         string incfile(params_.getContents());
548         string writefile;
549
550         Buffer const & buffer = features.buffer();
551
552         string const included_file = includedFilename(buffer, params_);
553
554         if (IsLyXFilename(included_file))
555                 writefile = ChangeExtension(included_file, ".sgml");
556         else
557                 writefile = included_file;
558
559         if (!features.nice() && !isVerbatim(params_)) {
560                 incfile = FileName(writefile).mangledFilename();
561                 writefile = MakeAbsPath(incfile,
562                                         buffer.getMasterBuffer()->temppath());
563         }
564
565         features.includeFile(include_label, writefile);
566
567         if (isVerbatim(params_))
568                 features.require("verbatim");
569
570         // Here we must do the fun stuff...
571         // Load the file in the include if it needs
572         // to be loaded:
573         if (loadIfNeeded(buffer, params_)) {
574                 // a file got loaded
575                 Buffer * const tmp = bufferlist.getBuffer(included_file);
576                 if (tmp) {
577                         // We must temporarily change features.buffer,
578                         // otherwise it would always be the master buffer,
579                         // and nested includes would not work.
580                         features.setBuffer(*tmp);
581                         tmp->validate(features);
582                         features.setBuffer(buffer);
583                 }
584         }
585 }
586
587
588 void InsetInclude::getLabelList(Buffer const & buffer,
589                                 std::vector<string> & list) const
590 {
591         if (loadIfNeeded(buffer, params_)) {
592                 string const included_file = includedFilename(buffer, params_);
593                 Buffer * tmp = bufferlist.getBuffer(included_file);
594                 tmp->setParentName("");
595                 tmp->getLabelList(list);
596                 tmp->setParentName(parentFilename(buffer));
597         }
598 }
599
600
601 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
602                                    std::vector<std::pair<string,string> > & keys) const
603 {
604         if (loadIfNeeded(buffer, params_)) {
605                 string const included_file = includedFilename(buffer, params_);
606                 Buffer * tmp = bufferlist.getBuffer(included_file);
607                 tmp->setParentName("");
608                 tmp->fillWithBibKeys(keys);
609                 tmp->setParentName(parentFilename(buffer));
610         }
611 }
612
613
614 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
615 {
616         BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
617
618         bool use_preview = false;
619         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
620                 lyx::graphics::PreviewImage const * pimage =
621                         preview_->getPreviewImage(*mi.base.bv->buffer());
622                 use_preview = pimage && pimage->image();
623         }
624
625         if (use_preview) {
626                 preview_->metrics(mi, dim);
627         } else {
628                 if (!set_label_) {
629                         set_label_ = true;
630                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
631                                        true);
632                 }
633                 button_.metrics(mi, dim);
634         }
635
636         Box b(0, dim.wid, -dim.asc, dim.des);
637         button_.setBox(b);
638
639         dim_ = dim;
640 }
641
642
643 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
644 {
645         setPosCache(pi, x, y);
646
647         BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
648
649         bool use_preview = false;
650         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
651                 lyx::graphics::PreviewImage const * pimage =
652                         preview_->getPreviewImage(*pi.base.bv->buffer());
653                 use_preview = pimage && pimage->image();
654         }
655
656         if (use_preview)
657                 preview_->draw(pi, x, y);
658         else
659                 button_.draw(pi, x, y);
660 }
661
662 bool InsetInclude::display() const
663 {
664         return type(params_) != INPUT;
665 }
666
667
668
669 //
670 // preview stuff
671 //
672
673 void InsetInclude::fileChanged() const
674 {
675         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
676         if (!buffer_ptr)
677                 return;
678
679         Buffer const & buffer = *buffer_ptr;
680         preview_->removePreview(buffer);
681         add_preview(*preview_.get(), *this, buffer);
682         preview_->startLoading(buffer);
683 }
684
685
686 namespace {
687
688 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
689 {
690         string const included_file = includedFilename(buffer, params);
691
692         return type(params) == INPUT && params.preview() &&
693                 IsFileReadable(included_file);
694 }
695
696
697 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
698 {
699         ostringstream os;
700         OutputParams runparams;
701         runparams.flavor = OutputParams::LATEX;
702         inset.latex(buffer, os, runparams);
703
704         return os.str();
705 }
706
707
708 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
709                  Buffer const & buffer)
710 {
711         InsetCommandParams const & params = inset.params();
712         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
713             preview_wanted(params, buffer)) {
714                 renderer.setAbsFile(includedFilename(buffer, params));
715                 string const snippet = latex_string(inset, buffer);
716                 renderer.addPreview(snippet, buffer);
717         }
718 }
719
720 } // namespace anon
721
722
723 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
724 {
725         Buffer const & buffer = ploader.buffer();
726         if (preview_wanted(params(), buffer)) {
727                 preview_->setAbsFile(includedFilename(buffer, params()));
728                 string const snippet = latex_string(*this, buffer);
729                 preview_->addPreview(snippet, ploader);
730         }
731 }
732
733
734 string const InsetIncludeMailer::name_("include");
735
736 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
737         : inset_(inset)
738 {}
739
740
741 string const InsetIncludeMailer::inset2string(Buffer const &) const
742 {
743         return params2string(inset_.params());
744 }
745
746
747 void InsetIncludeMailer::string2params(string const & in,
748                                        InsetCommandParams & params)
749 {
750         params = InsetCommandParams();
751         if (in.empty())
752                 return;
753
754         istringstream data(in);
755         LyXLex lex(0,0);
756         lex.setStream(data);
757
758         string name;
759         lex >> name;
760         if (!lex || name != name_)
761                 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
762
763         // This is part of the inset proper that is usually swallowed
764         // by LyXText::readInset
765         string id;
766         lex >> id;
767         if (!lex || id != "Include")
768                 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
769
770         InsetInclude inset(params);
771         inset.read(lex);
772         params = inset.params();
773 }
774
775
776 string const
777 InsetIncludeMailer::params2string(InsetCommandParams const & params)
778 {
779         InsetInclude inset(params);
780         ostringstream data;
781         data << name_ << ' ';
782         inset.write(data);
783         data << "\\end_inset\n";
784         return data.str();
785 }