]> git.lyx.org Git - lyx.git/blob - src/insets/insetinclude.C
Update on view-source feature (r13610), from Bo Peng (ben.bob@gmail.com)
[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 || runparams.dryrun)
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         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
411                         "latex" : "pdflatex";
412         if (isVerbatim(params_)) {
413                 incfile = latex_path(incfile);
414                 os << '\\' << params_.getCmdName() << '{' << incfile << '}';
415         } else if (type(params_) == INPUT) {
416                 runparams.exportdata->addExternalFile(tex_format, writefile,
417                                                       exportfile);
418
419                 // \input wants file with extension (default is .tex)
420                 if (!isLyXFilename(included_file)) {
421                         incfile = latex_path(incfile);
422                         os << '\\' << params_.getCmdName() << '{' << incfile << '}';
423                 } else {
424                 incfile = changeExtension(incfile, ".tex");
425                 incfile = latex_path(incfile);
426                         os << '\\' << params_.getCmdName() << '{'
427                            << incfile
428                            <<  '}';
429                 }
430         } else {
431                 runparams.exportdata->addExternalFile(tex_format, writefile,
432                                                       exportfile);
433
434                 // \include don't want extension and demands that the
435                 // file really have .tex
436                 incfile = changeExtension(incfile, string());
437                 incfile = latex_path(incfile);
438                 os << '\\' << params_.getCmdName() << '{'
439                    << incfile
440                    << '}';
441         }
442
443         return 0;
444 }
445
446
447 int InsetInclude::plaintext(Buffer const & buffer, ostream & os,
448                         OutputParams const &) const
449 {
450         if (isVerbatim(params_))
451                 os << getFileContents(includedFilename(buffer, params_));
452         return 0;
453 }
454
455
456 int InsetInclude::linuxdoc(Buffer const & buffer, ostream & os,
457                            OutputParams const & runparams) const
458 {
459         string incfile(params_.getContents());
460
461         // Do nothing if no file name has been specified
462         if (incfile.empty())
463                 return 0;
464
465         string const included_file = includedFilename(buffer, params_);
466
467         // write it to a file (so far the complete file)
468         string const exportfile = changeExtension(incfile, ".sgml");
469         string writefile = changeExtension(included_file, ".sgml");
470
471         if (loadIfNeeded(buffer, params_)) {
472                 Buffer * tmp = bufferlist.getBuffer(included_file);
473
474                 writefile = makeAbsPath(FileName(writefile).mangledFilename(),
475                                         buffer.getMasterBuffer()->temppath());
476                 if (!runparams.nice)
477                         incfile = writefile;
478
479                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
480                 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
481                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
482
483                 tmp->makeLinuxDocFile(writefile, runparams, true);
484         }
485
486         if (isVerbatim(params_)) {
487                 os << "<![CDATA["
488                    << getFileContents(included_file)
489                    << "]]>";
490         } else {
491                 runparams.exportdata->addExternalFile("linuxdoc", writefile,
492                                                       exportfile);
493                 os << '&' << include_label << ';';
494         }
495
496         return 0;
497 }
498
499
500 int InsetInclude::docbook(Buffer const & buffer, ostream & os,
501                           OutputParams const & runparams) const
502 {
503         string incfile(params_.getContents());
504
505         // Do nothing if no file name has been specified
506         if (incfile.empty())
507                 return 0;
508
509         string const included_file = includedFilename(buffer, params_);
510
511         // write it to a file (so far the complete file)
512         string const exportfile = changeExtension(incfile, ".sgml");
513         string writefile = changeExtension(included_file, ".sgml");
514
515         if (loadIfNeeded(buffer, params_)) {
516                 Buffer * tmp = bufferlist.getBuffer(included_file);
517
518                 string const mangled = FileName(writefile).mangledFilename();
519                 writefile = makeAbsPath(mangled,
520                                         buffer.getMasterBuffer()->temppath());
521                 if (!runparams.nice)
522                         incfile = mangled;
523
524                 lyxerr[Debug::LATEX] << "incfile:" << incfile << endl;
525                 lyxerr[Debug::LATEX] << "exportfile:" << exportfile << endl;
526                 lyxerr[Debug::LATEX] << "writefile:" << writefile << endl;
527
528                 tmp->makeDocBookFile(writefile, runparams, true);
529         }
530
531         runparams.exportdata->addExternalFile("docbook", writefile,
532                                               exportfile);
533         runparams.exportdata->addExternalFile("docbook-xml", writefile,
534                                               exportfile);
535
536         if (isVerbatim(params_)) {
537                 os << "<inlinegraphic fileref=\""
538                    << '&' << include_label << ';'
539                    << "\" format=\"linespecific\">";
540         } else
541                 os << '&' << include_label << ';';
542
543         return 0;
544 }
545
546
547 void InsetInclude::validate(LaTeXFeatures & features) const
548 {
549         string incfile(params_.getContents());
550         string writefile;
551
552         Buffer const & buffer = features.buffer();
553
554         string const included_file = includedFilename(buffer, params_);
555
556         if (isLyXFilename(included_file))
557                 writefile = changeExtension(included_file, ".sgml");
558         else
559                 writefile = included_file;
560
561         if (!features.runparams().nice && !isVerbatim(params_)) {
562                 incfile = FileName(writefile).mangledFilename();
563                 writefile = makeAbsPath(incfile,
564                                         buffer.getMasterBuffer()->temppath());
565         }
566
567         features.includeFile(include_label, writefile);
568
569         if (isVerbatim(params_))
570                 features.require("verbatim");
571
572         // Here we must do the fun stuff...
573         // Load the file in the include if it needs
574         // to be loaded:
575         if (loadIfNeeded(buffer, params_)) {
576                 // a file got loaded
577                 Buffer * const tmp = bufferlist.getBuffer(included_file);
578                 if (tmp) {
579                         // We must temporarily change features.buffer,
580                         // otherwise it would always be the master buffer,
581                         // and nested includes would not work.
582                         features.setBuffer(*tmp);
583                         tmp->validate(features);
584                         features.setBuffer(buffer);
585                 }
586         }
587 }
588
589
590 void InsetInclude::getLabelList(Buffer const & buffer,
591                                 std::vector<string> & list) const
592 {
593         if (loadIfNeeded(buffer, params_)) {
594                 string const included_file = includedFilename(buffer, params_);
595                 Buffer * tmp = bufferlist.getBuffer(included_file);
596                 tmp->setParentName("");
597                 tmp->getLabelList(list);
598                 tmp->setParentName(parentFilename(buffer));
599         }
600 }
601
602
603 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
604                                    std::vector<std::pair<string,string> > & keys) const
605 {
606         if (loadIfNeeded(buffer, params_)) {
607                 string const included_file = includedFilename(buffer, params_);
608                 Buffer * tmp = bufferlist.getBuffer(included_file);
609                 tmp->setParentName("");
610                 tmp->fillWithBibKeys(keys);
611                 tmp->setParentName(parentFilename(buffer));
612         }
613 }
614
615
616 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
617 {
618         BOOST_ASSERT(mi.base.bv && mi.base.bv->buffer());
619
620         bool use_preview = false;
621         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
622                 lyx::graphics::PreviewImage const * pimage =
623                         preview_->getPreviewImage(*mi.base.bv->buffer());
624                 use_preview = pimage && pimage->image();
625         }
626
627         if (use_preview) {
628                 preview_->metrics(mi, dim);
629         } else {
630                 if (!set_label_) {
631                         set_label_ = true;
632                         button_.update(getScreenLabel(*mi.base.bv->buffer()),
633                                        true);
634                 }
635                 button_.metrics(mi, dim);
636         }
637
638         Box b(0, dim.wid, -dim.asc, dim.des);
639         button_.setBox(b);
640
641         dim_ = dim;
642 }
643
644
645 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
646 {
647         setPosCache(pi, x, y);
648
649         BOOST_ASSERT(pi.base.bv && pi.base.bv->buffer());
650
651         bool use_preview = false;
652         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
653                 lyx::graphics::PreviewImage const * pimage =
654                         preview_->getPreviewImage(*pi.base.bv->buffer());
655                 use_preview = pimage && pimage->image();
656         }
657
658         if (use_preview)
659                 preview_->draw(pi, x, y);
660         else
661                 button_.draw(pi, x, y);
662 }
663
664 bool InsetInclude::display() const
665 {
666         return type(params_) != INPUT;
667 }
668
669
670
671 //
672 // preview stuff
673 //
674
675 void InsetInclude::fileChanged() const
676 {
677         Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
678         if (!buffer_ptr)
679                 return;
680
681         Buffer const & buffer = *buffer_ptr;
682         preview_->removePreview(buffer);
683         add_preview(*preview_.get(), *this, buffer);
684         preview_->startLoading(buffer);
685 }
686
687
688 namespace {
689
690 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
691 {
692         string const included_file = includedFilename(buffer, params);
693
694         return type(params) == INPUT && params.preview() &&
695                 isFileReadable(included_file);
696 }
697
698
699 string const latex_string(InsetInclude const & inset, Buffer const & buffer)
700 {
701         ostringstream os;
702         OutputParams runparams;
703         runparams.flavor = OutputParams::LATEX;
704         inset.latex(buffer, os, runparams);
705
706         return os.str();
707 }
708
709
710 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
711                  Buffer const & buffer)
712 {
713         InsetCommandParams const & params = inset.params();
714         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
715             preview_wanted(params, buffer)) {
716                 renderer.setAbsFile(includedFilename(buffer, params));
717                 string const snippet = latex_string(inset, buffer);
718                 renderer.addPreview(snippet, buffer);
719         }
720 }
721
722 } // namespace anon
723
724
725 void InsetInclude::addPreview(lyx::graphics::PreviewLoader & ploader) const
726 {
727         Buffer const & buffer = ploader.buffer();
728         if (preview_wanted(params(), buffer)) {
729                 preview_->setAbsFile(includedFilename(buffer, params()));
730                 string const snippet = latex_string(*this, buffer);
731                 preview_->addPreview(snippet, ploader);
732         }
733 }
734
735
736 string const InsetIncludeMailer::name_("include");
737
738 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)
739         : inset_(inset)
740 {}
741
742
743 string const InsetIncludeMailer::inset2string(Buffer const &) const
744 {
745         return params2string(inset_.params());
746 }
747
748
749 void InsetIncludeMailer::string2params(string const & in,
750                                        InsetCommandParams & params)
751 {
752         params = InsetCommandParams();
753         if (in.empty())
754                 return;
755
756         istringstream data(in);
757         LyXLex lex(0,0);
758         lex.setStream(data);
759
760         string name;
761         lex >> name;
762         if (!lex || name != name_)
763                 return print_mailer_error("InsetIncludeMailer", in, 1, name_);
764
765         // This is part of the inset proper that is usually swallowed
766         // by LyXText::readInset
767         string id;
768         lex >> id;
769         if (!lex || id != "Include")
770                 return print_mailer_error("InsetIncludeMailer", in, 2, "Include");
771
772         InsetInclude inset(params);
773         inset.read(lex);
774         params = inset.params();
775 }
776
777
778 string const
779 InsetIncludeMailer::params2string(InsetCommandParams const & params)
780 {
781         InsetInclude inset(params);
782         ostringstream data;
783         data << name_ << ' ';
784         inset.write(data);
785         data << "\\end_inset\n";
786         return data.str();
787 }