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