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