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