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