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