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