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