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