]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
2a8fdf7a599af796f52b3e22f4944576198248a1
[lyx.git] / src / insets / InsetInclude.cpp
1 /**
2  * \file InsetInclude.cpp
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  * \author Richard Heck (conversion to InsetCommand)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetInclude.h"
15
16 #include "Buffer.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Cursor.h"
22 #include "DispatchResult.h"
23 #include "ErrorList.h"
24 #include "Exporter.h"
25 #include "Format.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "LayoutFile.h"
30 #include "LayoutModuleList.h"
31 #include "LyX.h"
32 #include "LyXFunc.h"
33 #include "LyXRC.h"
34 #include "Lexer.h"
35 #include "MetricsInfo.h"
36 #include "OutputParams.h"
37 #include "TextClass.h"
38 #include "TocBackend.h"
39
40 #include "frontends/alert.h"
41 #include "frontends/Painter.h"
42
43 #include "graphics/PreviewImage.h"
44 #include "graphics/PreviewLoader.h"
45
46 #include "insets/InsetLabel.h"
47 #include "insets/InsetListingsParams.h"
48 #include "insets/RenderPreview.h"
49
50 #include "support/convert.h"
51 #include "support/debug.h"
52 #include "support/docstream.h"
53 #include "support/FileNameList.h"
54 #include "support/filetools.h"
55 #include "support/gettext.h"
56 #include "support/lassert.h"
57 #include "support/lstrings.h" // contains
58 #include "support/lyxalgo.h"
59
60 #include <boost/bind.hpp>
61
62 using namespace std;
63 using namespace lyx::support;
64
65 namespace lyx {
66
67 namespace Alert = frontend::Alert;
68
69
70 namespace {
71
72 docstring const uniqueID()
73 {
74         static unsigned int seed = 1000;
75         return "file" + convert<docstring>(++seed);
76 }
77
78
79 /// the type of inclusion
80 enum Types {
81         INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
82 };
83
84
85 Types type(string const & s)
86 {
87         if (s == "input")
88                 return INPUT;
89         if (s == "verbatiminput")
90                 return VERB;
91         if (s == "verbatiminput*")
92                 return VERBAST;
93         if (s == "lstinputlisting")
94                 return LISTINGS;
95         if (s == "include")
96                 return INCLUDE;
97         return NONE;
98 }
99
100
101 Types type(InsetCommandParams const & params)
102 {
103         return type(params.getCmdName());
104 }
105
106
107 bool isListings(InsetCommandParams const & params)
108 {
109         return type(params) == LISTINGS;
110 }
111
112
113 bool isVerbatim(InsetCommandParams const & params)
114 {
115         Types const t = type(params);
116         return t == VERB || t == VERBAST;
117 }
118
119
120 bool isInputOrInclude(InsetCommandParams const & params)
121 {
122         Types const t = type(params);
123         return t == INPUT || t == INCLUDE;
124 }
125
126
127 FileName const masterFileName(Buffer const & buffer)
128 {
129         return buffer.masterBuffer()->fileName();
130 }
131
132
133 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
134
135
136 string const parentFilename(Buffer const & buffer)
137 {
138         return buffer.absFileName();
139 }
140
141
142 FileName const includedFilename(Buffer const & buffer,
143                               InsetCommandParams const & params)
144 {
145         return makeAbsPath(to_utf8(params["filename"]),
146                         onlyPath(parentFilename(buffer)));
147 }
148
149
150 InsetLabel * createLabel(docstring const & label_str)
151 {
152         if (label_str.empty())
153                 return 0;
154         InsetCommandParams icp(LABEL_CODE);
155         icp["name"] = label_str;
156         return new InsetLabel(icp);
157 }
158
159 } // namespace anon
160
161
162 InsetInclude::InsetInclude(InsetCommandParams const & p)
163         : InsetCommand(p, "include"), include_label(uniqueID()),
164           preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
165           set_label_(false), label_(0), child_buffer_(0)
166 {
167         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
168
169         if (isListings(params())) {
170                 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
171                 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
172         }
173 }
174
175
176 InsetInclude::InsetInclude(InsetInclude const & other)
177         : InsetCommand(other), include_label(other.include_label),
178           preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
179           set_label_(false), label_(0), child_buffer_(0)
180 {
181         preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
182
183         if (other.label_)
184                 label_ = new InsetLabel(*other.label_);
185 }
186
187
188 InsetInclude::~InsetInclude()
189 {
190         delete label_;
191 }
192
193
194 void InsetInclude::setBuffer(Buffer & buffer)
195 {
196         InsetCommand::setBuffer(buffer);
197         if (label_)
198                 label_->setBuffer(buffer);
199 }
200
201
202 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
203 {
204         // FIXME
205         // This is only correct for the case of listings, but it'll do for now.
206         // In the other cases, this second parameter should just be empty.
207         static ParamInfo param_info_;
208         if (param_info_.empty()) {
209                 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
210                 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
211         }
212         return param_info_;
213 }
214
215
216 bool InsetInclude::isCompatibleCommand(string const & s)
217 {
218         return type(s) != NONE;
219 }
220
221
222 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
223 {
224         LASSERT(cur.buffer() == &buffer(), return);
225         switch (cmd.action) {
226
227         case LFUN_INSET_EDIT: {
228                 editIncluded(to_utf8(params()["filename"]));
229                 break;
230         }
231
232         case LFUN_INSET_MODIFY: {
233                 // It should be OK just to invalidate the cache is setParams()
234                 // If not....
235                 // child_buffer_ = 0;
236                 InsetCommandParams p(INCLUDE_CODE);
237                 if (cmd.getArg(0) == "changetype") {
238                         InsetCommand::doDispatch(cur, cmd);
239                         p = params();
240                 } else
241                         InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
242                 if (!p.getCmdName().empty()) {
243                         if (isListings(p)){
244                                 InsetListingsParams new_params(to_utf8(p["lstparams"]));
245                                 docstring const new_label =
246                                         from_utf8(new_params.getParamValue("label"));
247                                 
248                                 if (new_label.empty()) {
249                                         delete label_;
250                                         label_ = 0;
251                                 } else {
252                                         docstring old_label;
253                                         if (label_) 
254                                                 old_label = label_->getParam("name");
255                                         else {
256                                                 label_ = createLabel(new_label);
257                                                 label_->setBuffer(buffer());
258                                         }                                       
259
260                                         if (new_label != old_label) {
261                                                 label_->updateCommand(new_label);
262                                                 // the label might have been adapted (duplicate)
263                                                 if (new_label != label_->getParam("name")) {
264                                                         new_params.addParam("label", "{" + 
265                                                                 to_utf8(label_->getParam("name")) + "}", true);
266                                                         p["lstparams"] = from_utf8(new_params.params());
267                                                 }
268                                         }
269                                 }
270                         }
271                         setParams(p);
272                 } else
273                         cur.noUpdate();
274                 break;
275         }
276
277         //pass everything else up the chain
278         default:
279                 InsetCommand::doDispatch(cur, cmd);
280                 break;
281         }
282 }
283
284
285 void InsetInclude::editIncluded(string const & file)
286 {
287         string const ext = support::getExtension(file);
288         if (ext == "lyx") {
289                 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
290                 lyx::dispatch(fr);
291         } else
292                 // tex file or other text file in verbatim mode
293                 formats.edit(buffer(),
294                         support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
295                         "text");
296 }
297
298
299 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
300                 FuncStatus & flag) const
301 {
302         switch (cmd.action) {
303
304         case LFUN_INSET_EDIT:
305         case LFUN_INSET_MODIFY:
306                 flag.setEnabled(true);
307                 return true;
308
309         default:
310                 return InsetCommand::getStatus(cur, cmd, flag);
311         }
312 }
313
314
315 void InsetInclude::setParams(InsetCommandParams const & p)
316 {
317         // invalidate the cache
318         child_buffer_ = 0;
319
320         InsetCommand::setParams(p);
321         set_label_ = false;
322
323         if (preview_->monitoring())
324                 preview_->stopMonitoring();
325
326         if (type(params()) == INPUT)
327                 add_preview(*preview_, *this, buffer());
328
329         buffer().updateBibfilesCache();
330 }
331
332
333 docstring InsetInclude::screenLabel() const
334 {
335         docstring temp;
336
337         switch (type(params())) {
338                 case INPUT:
339                         temp = buffer().B_("Input");
340                         break;
341                 case VERB:
342                         temp = buffer().B_("Verbatim Input");
343                         break;
344                 case VERBAST:
345                         temp = buffer().B_("Verbatim Input*");
346                         break;
347                 case INCLUDE:
348                         temp = buffer().B_("Include");
349                         break;
350                 case LISTINGS:
351                         temp = listings_label_;
352                         break;
353                 case NONE:
354                         LASSERT(false, /**/);
355         }
356
357         temp += ": ";
358
359         if (params()["filename"].empty())
360                 temp += "???";
361         else
362                 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
363
364         return temp;
365 }
366
367
368 Buffer * InsetInclude::getChildBuffer() const
369 {
370         Buffer * childBuffer = loadIfNeeded(); 
371
372         // FIXME: recursive includes
373         return (childBuffer == &buffer()) ? 0 : childBuffer;
374 }
375
376
377 Buffer * InsetInclude::loadIfNeeded() const
378 {
379         // Don't try to load it again if we failed before.
380         if (failedtoload_ || isVerbatim(params()) || isListings(params()))
381                 return 0;
382
383         // Use cached Buffer if possible.
384         if (child_buffer_ != 0) {
385                 if (theBufferList().isLoaded(child_buffer_))
386                         return child_buffer_;
387                 // Buffer vanished, so invalidate cache and try to reload.
388                 child_buffer_ = 0;
389         }
390
391         string const parent_filename = buffer().absFileName();
392         FileName const included_file = 
393                 makeAbsPath(to_utf8(params()["filename"]), onlyPath(parent_filename));
394
395         if (!isLyXFilename(included_file.absFilename()))
396                 return 0;
397
398         Buffer * child = theBufferList().getBuffer(included_file);
399         if (!child) {
400                 // the readonly flag can/will be wrong, not anymore I think.
401                 if (!included_file.exists())
402                         return 0;
403
404                 child = theBufferList().newBuffer(included_file.absFilename());
405                 if (!child)
406                         // Buffer creation is not possible.
407                         return 0;
408
409                 if (!child->loadLyXFile(included_file)) {
410                         failedtoload_ = true;
411                         //close the buffer we just opened
412                         theBufferList().release(child);
413                         return 0;
414                 }
415         
416                 if (!child->errorList("Parse").empty()) {
417                         // FIXME: Do something.
418                 }
419         }
420         child->setParent(&buffer());
421         // Cache the child buffer.
422         child_buffer_ = child;
423         return child;
424 }
425
426
427 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
428 {
429         string incfile = to_utf8(params()["filename"]);
430
431         // Do nothing if no file name has been specified
432         if (incfile.empty())
433                 return 0;
434
435         FileName const included_file = includedFilename(buffer(), params());
436
437         // Check we're not trying to include ourselves.
438         // FIXME RECURSIVE INCLUDE
439         // This isn't sufficient, as the inclusion could be downstream.
440         // But it'll have to do for now.
441         if (isInputOrInclude(params()) &&
442                 buffer().absFileName() == included_file.absFilename())
443         {
444                 Alert::error(_("Recursive input"),
445                                bformat(_("Attempted to include file %1$s in itself! "
446                                "Ignoring inclusion."), from_utf8(incfile)));
447                 return 0;
448         }
449
450         Buffer const * const masterBuffer = buffer().masterBuffer();
451
452         // if incfile is relative, make it relative to the master
453         // buffer directory.
454         if (!FileName::isAbsolute(incfile)) {
455                 // FIXME UNICODE
456                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
457                                               from_utf8(masterBuffer->filePath())));
458         }
459
460         // write it to a file (so far the complete file)
461         string exportfile;
462         string mangled;
463         // bug 5681
464         if (type(params()) == LISTINGS) {
465                 exportfile = incfile;
466                 mangled = DocFileName(included_file).mangledFilename();
467         } else {
468                 exportfile = changeExtension(incfile, ".tex");
469                 mangled = DocFileName(changeExtension(included_file.absFilename(), ".tex")).
470                         mangledFilename();
471         }
472
473         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
474
475         if (!runparams.nice)
476                 incfile = mangled;
477         else if (!isValidLaTeXFilename(incfile)) {
478                 frontend::Alert::warning(_("Invalid filename"),
479                                          _("The following filename is likely to cause trouble "
480                                            "when running the exported file through LaTeX: ") +
481                                             from_utf8(incfile));
482         }
483         LYXERR(Debug::LATEX, "incfile:" << incfile);
484         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
485         LYXERR(Debug::LATEX, "writefile:" << writefile);
486
487         if (runparams.inComment || runparams.dryrun) {
488                 //Don't try to load or copy the file if we're
489                 //in a comment or doing a dryrun
490         } else if (isInputOrInclude(params()) &&
491                  isLyXFilename(included_file.absFilename())) {
492                 //if it's a LyX file and we're inputting or including,
493                 //try to load it so we can write the associated latex
494                 if (!loadIfNeeded())
495                         return false;
496
497                 Buffer * tmp = theBufferList().getBuffer(included_file);
498
499                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
500                         // FIXME UNICODE
501                         docstring text = bformat(_("Included file `%1$s'\n"
502                                 "has textclass `%2$s'\n"
503                                 "while parent file has textclass `%3$s'."),
504                                 included_file.displayName(),
505                                 from_utf8(tmp->params().documentClass().name()),
506                                 from_utf8(masterBuffer->params().documentClass().name()));
507                         Alert::warning(_("Different textclasses"), text, true);
508                 }
509
510                 // Make sure modules used in child are all included in master
511                 // FIXME It might be worth loading the children's modules into the master
512                 // over in BufferParams rather than doing this check.
513                 LayoutModuleList const masterModules = masterBuffer->params().getModules();
514                 LayoutModuleList const childModules = tmp->params().getModules();
515                 LayoutModuleList::const_iterator it = childModules.begin();
516                 LayoutModuleList::const_iterator end = childModules.end();
517                 for (; it != end; ++it) {
518                         string const module = *it;
519                         LayoutModuleList::const_iterator found =
520                                 find(masterModules.begin(), masterModules.end(), module);
521                         if (found == masterModules.end()) {
522                                 docstring text = bformat(_("Included file `%1$s'\n"
523                                         "uses module `%2$s'\n"
524                                         "which is not used in parent file."),
525                                         included_file.displayName(), from_utf8(module));
526                                 Alert::warning(_("Module not found"), text);
527                         }
528                 }
529
530                 tmp->markDepClean(masterBuffer->temppath());
531
532                 // FIXME: handle non existing files
533                 // FIXME: Second argument is irrelevant!
534                 // since only_body is true, makeLaTeXFile will not look at second
535                 // argument. Should we set it to string(), or should makeLaTeXFile
536                 // make use of it somehow? (JMarc 20031002)
537                 // The included file might be written in a different encoding
538                 Encoding const * const oldEnc = runparams.encoding;
539                 runparams.encoding = &tmp->params().encoding();
540                 tmp->makeLaTeXFile(writefile,
541                                    masterFileName(buffer()).onlyPath().absFilename(),
542                                    runparams, false);
543                 runparams.encoding = oldEnc;
544         } else {
545                 // In this case, it's not a LyX file, so we copy the file
546                 // to the temp dir, so that .aux files etc. are not created
547                 // in the original dir. Files included by this file will be
548                 // found via input@path, see ../Buffer.cpp.
549                 unsigned long const checksum_in  = included_file.checksum();
550                 unsigned long const checksum_out = writefile.checksum();
551
552                 if (checksum_in != checksum_out) {
553                         if (!included_file.copyTo(writefile)) {
554                                 // FIXME UNICODE
555                                 LYXERR(Debug::LATEX,
556                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
557                                                                   "into the temporary directory."),
558                                                    from_utf8(included_file.absFilename()))));
559                                 return 0;
560                         }
561                 }
562         }
563
564         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
565                         "latex" : "pdflatex";
566         switch (type(params())) {
567         case VERB:
568         case VERBAST: {
569                 incfile = latex_path(incfile);
570                 // FIXME UNICODE
571                 os << '\\' << from_ascii(params().getCmdName()) << '{'
572                    << from_utf8(incfile) << '}';
573                 break;
574         } 
575         case INPUT: {
576                 runparams.exportdata->addExternalFile(tex_format, writefile,
577                                                       exportfile);
578
579                 // \input wants file with extension (default is .tex)
580                 if (!isLyXFilename(included_file.absFilename())) {
581                         incfile = latex_path(incfile);
582                         // FIXME UNICODE
583                         os << '\\' << from_ascii(params().getCmdName())
584                            << '{' << from_utf8(incfile) << '}';
585                 } else {
586                 incfile = changeExtension(incfile, ".tex");
587                 incfile = latex_path(incfile);
588                         // FIXME UNICODE
589                         os << '\\' << from_ascii(params().getCmdName())
590                            << '{' << from_utf8(incfile) <<  '}';
591                 }
592                 break;
593         } 
594         case LISTINGS: {
595                 os << '\\' << from_ascii(params().getCmdName());
596                 string const opt = to_utf8(params()["lstparams"]);
597                 // opt is set in QInclude dialog and should have passed validation.
598                 InsetListingsParams params(opt);
599                 if (!params.params().empty())
600                         os << "[" << from_utf8(params.params()) << "]";
601                 os << '{'  << from_utf8(incfile) << '}';
602                 break;
603         } 
604         case INCLUDE: {
605                 runparams.exportdata->addExternalFile(tex_format, writefile,
606                                                       exportfile);
607
608                 // \include don't want extension and demands that the
609                 // file really have .tex
610                 incfile = changeExtension(incfile, string());
611                 incfile = latex_path(incfile);
612                 // FIXME UNICODE
613                 os << '\\' << from_ascii(params().getCmdName()) << '{'
614                    << from_utf8(incfile) << '}';
615                 break;
616         }
617         case NONE:
618                 break;
619         }
620
621         return 0;
622 }
623
624
625 docstring InsetInclude::xhtml(odocstream & os, OutputParams const &rp) const
626 {
627         if (rp.inComment)
628                  return docstring();
629
630         // For verbatim and listings, we just include the contents of the file as-is.
631         // In the case of listings, we wrap it in <pre>.
632         bool const listing = isListings(params());
633         if (listing || isVerbatim(params())) {
634                 if (listing)
635                         os << "<pre>\n";
636                 // FIXME: We don't know the encoding of the file, default to UTF-8.
637                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
638                 if (listing)
639                         os << "</pre>\n";
640                 return docstring();
641         }
642
643         // We don't (yet) know how to Input or Include non-LyX files.
644         // (If we wanted to get really arcane, we could run some tex2html
645         // converter on the included file. But that's just masochistic.)
646         string const parent_filename = buffer().absFileName();
647         FileName const included_file = 
648                 makeAbsPath(to_utf8(params()["filename"]), onlyPath(parent_filename));
649         if (!isLyXFilename(included_file.absFilename())) {
650                 frontend::Alert::warning(_("Unsupported Inclusion"),
651                                          _("LyX does not know how to include non-LyX files when"
652                                            "generating HTML output. Offending file: ") +
653                                             params()["filename"]);
654                 return docstring();
655         }
656
657         // In the other cases, we will generate the HTML and include it.
658
659         // Check we're not trying to include ourselves.
660         // FIXME RECURSIVE INCLUDE
661         if (buffer().absFileName() == included_file.absFilename()) {
662                 Alert::error(_("Recursive input"),
663                                bformat(_("Attempted to include file %1$s in itself! "
664                                "Ignoring inclusion."), params()["filename"]));
665                 return docstring();
666         }
667
668         Buffer const * const ibuf = loadIfNeeded();
669         if (!ibuf)
670                 return docstring();
671         ibuf->writeLyXHTMLSource(os, rp, true);
672         return docstring();
673 }
674
675
676 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
677 {
678         if (isVerbatim(params()) || isListings(params())) {
679                 os << '[' << screenLabel() << '\n';
680                 // FIXME: We don't know the encoding of the file, default to UTF-8.
681                 os << includedFilename(buffer(), params()).fileContents("UTF-8");
682                 os << "\n]";
683                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
684         } else {
685                 docstring const str = '[' + screenLabel() + ']';
686                 os << str;
687                 return str.size();
688         }
689 }
690
691
692 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
693 {
694         string incfile = to_utf8(params()["filename"]);
695
696         // Do nothing if no file name has been specified
697         if (incfile.empty())
698                 return 0;
699
700         string const included_file = includedFilename(buffer(), params()).absFilename();
701
702         // Check we're not trying to include ourselves.
703         // FIXME RECURSIVE INCLUDE
704         // This isn't sufficient, as the inclusion could be downstream.
705         // But it'll have to do for now.
706         if (buffer().absFileName() == included_file) {
707                 Alert::error(_("Recursive input"),
708                                bformat(_("Attempted to include file %1$s in itself! "
709                                "Ignoring inclusion."), from_utf8(incfile)));
710                 return 0;
711         }
712
713         // write it to a file (so far the complete file)
714         string const exportfile = changeExtension(incfile, ".sgml");
715         DocFileName writefile(changeExtension(included_file, ".sgml"));
716
717         if (loadIfNeeded()) {
718                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
719
720                 string const mangled = writefile.mangledFilename();
721                 writefile = makeAbsPath(mangled,
722                                         buffer().masterBuffer()->temppath());
723                 if (!runparams.nice)
724                         incfile = mangled;
725
726                 LYXERR(Debug::LATEX, "incfile:" << incfile);
727                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
728                 LYXERR(Debug::LATEX, "writefile:" << writefile);
729
730                 tmp->makeDocBookFile(writefile, runparams, true);
731         }
732
733         runparams.exportdata->addExternalFile("docbook", writefile,
734                                               exportfile);
735         runparams.exportdata->addExternalFile("docbook-xml", writefile,
736                                               exportfile);
737
738         if (isVerbatim(params()) || isListings(params())) {
739                 os << "<inlinegraphic fileref=\""
740                    << '&' << include_label << ';'
741                    << "\" format=\"linespecific\">";
742         } else
743                 os << '&' << include_label << ';';
744
745         return 0;
746 }
747
748
749 void InsetInclude::validate(LaTeXFeatures & features) const
750 {
751         string incfile = to_utf8(params()["filename"]);
752         string writefile;
753
754         LASSERT(&buffer() == &features.buffer(), /**/);
755
756         string const included_file =
757                 includedFilename(buffer(), params()).absFilename();
758
759         if (isLyXFilename(included_file))
760                 writefile = changeExtension(included_file, ".sgml");
761         else
762                 writefile = included_file;
763
764         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
765                 incfile = DocFileName(writefile).mangledFilename();
766                 writefile = makeAbsPath(incfile,
767                                         buffer().masterBuffer()->temppath()).absFilename();
768         }
769
770         features.includeFile(include_label, writefile);
771
772         if (isVerbatim(params()))
773                 features.require("verbatim");
774         else if (isListings(params()))
775                 features.require("listings");
776
777         // Here we must do the fun stuff...
778         // Load the file in the include if it needs
779         // to be loaded:
780         if (loadIfNeeded()) {
781                 // a file got loaded
782                 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
783                 // make sure the buffer isn't us
784                 // FIXME RECURSIVE INCLUDES
785                 // This is not sufficient, as recursive includes could be
786                 // more than a file away. But it will do for now.
787                 if (tmp && tmp != &buffer()) {
788                         // We must temporarily change features.buffer,
789                         // otherwise it would always be the master buffer,
790                         // and nested includes would not work.
791                         features.setBuffer(*tmp);
792                         tmp->validate(features);
793                         features.setBuffer(buffer());
794                 }
795         }
796 }
797
798
799 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
800         InsetIterator const & /*di*/) const
801 {
802         if (loadIfNeeded()) {
803                 string const included_file = includedFilename(buffer(), params()).absFilename();
804                 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
805                 BiblioInfo const & newkeys = tmp->localBibInfo();
806                 keys.mergeBiblioInfo(newkeys);
807         }
808 }
809
810
811 void InsetInclude::updateBibfilesCache()
812 {
813         Buffer const * const child = getChildBuffer();
814         if (child)
815                 child->updateBibfilesCache(Buffer::UpdateChildOnly);
816 }
817
818
819 support::FileNameList const &
820         InsetInclude::getBibfilesCache() const
821 {
822         Buffer const * const child = getChildBuffer();
823         if (child)
824                 return child->getBibfilesCache(Buffer::UpdateChildOnly);
825
826         static support::FileNameList const empty;
827         return empty;
828 }
829
830
831 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
832 {
833         LASSERT(mi.base.bv, /**/);
834
835         bool use_preview = false;
836         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
837                 graphics::PreviewImage const * pimage =
838                         preview_->getPreviewImage(mi.base.bv->buffer());
839                 use_preview = pimage && pimage->image();
840         }
841
842         if (use_preview) {
843                 preview_->metrics(mi, dim);
844         } else {
845                 if (!set_label_) {
846                         set_label_ = true;
847                         button_.update(screenLabel(), true);
848                 }
849                 button_.metrics(mi, dim);
850         }
851
852         Box b(0, dim.wid, -dim.asc, dim.des);
853         button_.setBox(b);
854 }
855
856
857 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
858 {
859         LASSERT(pi.base.bv, /**/);
860
861         bool use_preview = false;
862         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
863                 graphics::PreviewImage const * pimage =
864                         preview_->getPreviewImage(pi.base.bv->buffer());
865                 use_preview = pimage && pimage->image();
866         }
867
868         if (use_preview)
869                 preview_->draw(pi, x, y);
870         else
871                 button_.draw(pi, x, y);
872 }
873
874
875 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
876 {
877         return from_ascii("context-include");
878 }
879
880
881 Inset::DisplayType InsetInclude::display() const
882 {
883         return type(params()) == INPUT ? Inline : AlignCenter;
884 }
885
886
887
888 //
889 // preview stuff
890 //
891
892 void InsetInclude::fileChanged() const
893 {
894         Buffer const * const buffer = updateFrontend();
895         if (!buffer)
896                 return;
897
898         preview_->removePreview(*buffer);
899         add_preview(*preview_.get(), *this, *buffer);
900         preview_->startLoading(*buffer);
901 }
902
903
904 namespace {
905
906 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
907 {
908         FileName const included_file = includedFilename(buffer, params);
909
910         return type(params) == INPUT && params.preview() &&
911                 included_file.isReadableFile();
912 }
913
914
915 docstring latexString(InsetInclude const & inset)
916 {
917         odocstringstream os;
918         // We don't need to set runparams.encoding since this will be done
919         // by latex() anyway.
920         OutputParams runparams(0);
921         runparams.flavor = OutputParams::LATEX;
922         inset.latex(os, runparams);
923
924         return os.str();
925 }
926
927
928 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
929                  Buffer const & buffer)
930 {
931         InsetCommandParams const & params = inset.params();
932         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
933             preview_wanted(params, buffer)) {
934                 renderer.setAbsFile(includedFilename(buffer, params));
935                 docstring const snippet = latexString(inset);
936                 renderer.addPreview(snippet, buffer);
937         }
938 }
939
940 } // namespace anon
941
942
943 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
944 {
945         Buffer const & buffer = ploader.buffer();
946         if (!preview_wanted(params(), buffer))
947                 return;
948         preview_->setAbsFile(includedFilename(buffer, params()));
949         docstring const snippet = latexString(*this);
950         preview_->addPreview(snippet, ploader);
951 }
952
953
954 void InsetInclude::addToToc(DocIterator const & cpit)
955 {
956         TocBackend & backend = buffer().tocBackend();
957
958         if (isListings(params())) {
959                 if (label_)
960                         label_->addToToc(cpit);
961
962                 InsetListingsParams p(to_utf8(params()["lstparams"]));
963                 string caption = p.getParamValue("caption");
964                 if (caption.empty())
965                         return;
966                 Toc & toc = backend.toc("listing");
967                 docstring str = convert<docstring>(toc.size() + 1)
968                         + ". " +  from_utf8(caption);
969                 DocIterator pit = cpit;
970                 toc.push_back(TocItem(pit, 0, str));
971                 return;
972         }
973         Buffer const * const childbuffer = getChildBuffer();
974         if (!childbuffer)
975                 return;
976
977         Toc & toc = backend.toc("child");
978         docstring str = childbuffer->fileName().displayName();
979         toc.push_back(TocItem(cpit, 0, str));
980
981         TocList & toclist = backend.tocs();
982         childbuffer->tocBackend().update();
983         TocList const & childtoclist = childbuffer->tocBackend().tocs();
984         TocList::const_iterator it = childtoclist.begin();
985         TocList::const_iterator const end = childtoclist.end();
986         for(; it != end; ++it)
987                 toclist[it->first].insert(toclist[it->first].end(),
988                         it->second.begin(), it->second.end());
989 }
990
991
992 void InsetInclude::updateCommand()
993 {
994         if (!label_)
995                 return;
996
997         docstring old_label = label_->getParam("name");
998         label_->updateCommand(old_label, false);
999         // the label might have been adapted (duplicate)
1000         docstring new_label = label_->getParam("name");
1001         if (old_label == new_label)
1002                 return;
1003
1004         // update listings parameters...
1005         InsetCommandParams p(INCLUDE_CODE);
1006         p = params();
1007         InsetListingsParams par(to_utf8(params()["lstparams"]));
1008         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1009         p["lstparams"] = from_utf8(par.params());
1010         setParams(p);   
1011 }
1012
1013 void InsetInclude::updateLabels(ParIterator const & it)
1014 {
1015         Buffer const * const childbuffer = getChildBuffer();
1016         if (childbuffer) {
1017                 childbuffer->updateLabels(Buffer::UpdateChildOnly);
1018                 return;
1019         }
1020         if (!isListings(params()))
1021                 return;
1022
1023         if (label_)
1024                 label_->updateLabels(it);
1025
1026         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1027         if (par.getParamValue("caption").empty()) {
1028                 listings_label_ = buffer().B_("Program Listing");
1029                 return;
1030         }
1031         Buffer const & master = *buffer().masterBuffer();
1032         Counters & counters = master.params().documentClass().counters();
1033         docstring const cnt = from_ascii("listing");
1034         listings_label_ = master.B_("Program Listing");
1035         if (counters.hasCounter(cnt)) {
1036                 counters.step(cnt);
1037                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1038         }
1039 }
1040
1041
1042 } // namespace lyx