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