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