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