]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInclude.cpp
sk.po update
[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, temp = buffer().B_("Unknown"));
392                         break;
393         }
394
395         temp += ": ";
396
397         if (params()["filename"].empty())
398                 temp += "???";
399         else
400                 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
401
402         return temp;
403 }
404
405
406 Buffer * InsetInclude::getChildBuffer() const
407 {
408         Buffer * childBuffer = loadIfNeeded(); 
409
410         // FIXME: recursive includes
411         return (childBuffer == &buffer()) ? 0 : childBuffer;
412 }
413
414
415 Buffer * InsetInclude::loadIfNeeded() const
416 {
417         // This is for background export and preview. We don't even want to
418         // try to load the cloned child document again.
419         if (buffer().isClone())
420                 return child_buffer_;
421         
422         // Don't try to load it again if we failed before.
423         if (failedtoload_ || isVerbatim(params()) || isListings(params()))
424                 return 0;
425
426         FileName const included_file = includedFileName(buffer(), params());
427         // Use cached Buffer if possible.
428         if (child_buffer_ != 0) {
429                 if (theBufferList().isLoaded(child_buffer_)
430                 // additional sanity check: make sure the Buffer really is
431                     // associated with the file we want.
432                     && child_buffer_ == theBufferList().getBuffer(included_file))
433                         return child_buffer_;
434                 // Buffer vanished, so invalidate cache and try to reload.
435                 child_buffer_ = 0;
436         }
437
438         if (!isLyXFileName(included_file.absFileName()))
439                 return 0;
440
441         Buffer * child = theBufferList().getBuffer(included_file);
442         if (!child) {
443                 // the readonly flag can/will be wrong, not anymore I think.
444                 if (!included_file.exists())
445                         return 0;
446
447                 child = theBufferList().newBuffer(included_file.absFileName());
448                 if (!child)
449                         // Buffer creation is not possible.
450                         return 0;
451
452                 // Set parent before loading, such that macros can be tracked
453                 child->setParent(&buffer());
454
455                 if (child->loadLyXFile() != Buffer::ReadSuccess) {
456                         failedtoload_ = true;
457                         child->setParent(0);
458                         //close the buffer we just opened
459                         theBufferList().release(child);
460                         return 0;
461                 }
462
463                 if (!child->errorList("Parse").empty()) {
464                         // FIXME: Do something.
465                 }
466         } else {
467                 // The file was already loaded, so, simply
468                 // inform parent buffer about local macros.
469                 Buffer const * parent = &buffer();
470                 child->setParent(parent);
471                 MacroNameSet macros;
472                 child->listMacroNames(macros);
473                 MacroNameSet::const_iterator cit = macros.begin();
474                 MacroNameSet::const_iterator end = macros.end();
475                 for (; cit != end; ++cit)
476                         parent->usermacros.insert(*cit);
477         }
478
479         // Cache the child buffer.
480         child_buffer_ = child;
481         return child;
482 }
483
484
485 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
486 {
487         string incfile = to_utf8(params()["filename"]);
488
489         // Do nothing if no file name has been specified
490         if (incfile.empty())
491                 return;
492
493         FileName const included_file = includedFileName(buffer(), params());
494
495         // Check we're not trying to include ourselves.
496         // FIXME RECURSIVE INCLUDE
497         // This isn't sufficient, as the inclusion could be downstream.
498         // But it'll have to do for now.
499         if (isInputOrInclude(params()) &&
500                 buffer().absFileName() == included_file.absFileName())
501         {
502                 Alert::error(_("Recursive input"),
503                                bformat(_("Attempted to include file %1$s in itself! "
504                                "Ignoring inclusion."), from_utf8(incfile)));
505                 return;
506         }
507
508         Buffer const * const masterBuffer = buffer().masterBuffer();
509
510         // if incfile is relative, make it relative to the master
511         // buffer directory.
512         if (!FileName::isAbsolute(incfile)) {
513                 // FIXME UNICODE
514                 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
515                                               from_utf8(masterBuffer->filePath())));
516         }
517
518         string exppath = incfile;
519         if (!runparams.export_folder.empty()) {
520                 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
521                 FileName(exppath).onlyPath().createPath();
522         }
523
524         // write it to a file (so far the complete file)
525         string exportfile;
526         string mangled;
527         // bug 5681
528         if (type(params()) == LISTINGS) {
529                 exportfile = exppath;
530                 mangled = DocFileName(included_file).mangledFileName();
531         } else {
532                 exportfile = changeExtension(exppath, ".tex");
533                 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
534                         mangledFileName();
535         }
536
537         if (!runparams.nice)
538                 incfile = mangled;
539         else if (!isValidLaTeXFileName(incfile)) {
540                 frontend::Alert::warning(_("Invalid filename"),
541                         _("The following filename will cause troubles "
542                                 "when running the exported file through LaTeX: ") +
543                         from_utf8(incfile));
544         } else if (!isValidDVIFileName(incfile)) {
545                 frontend::Alert::warning(_("Problematic filename for DVI"),
546                         _("The following filename can cause troubles "
547                                 "when running the exported file through LaTeX "
548                                 "and opening the resulting DVI: ") +
549                         from_utf8(incfile), true);
550         }
551
552         FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
553
554         LYXERR(Debug::LATEX, "incfile:" << incfile);
555         LYXERR(Debug::LATEX, "exportfile:" << exportfile);
556         LYXERR(Debug::LATEX, "writefile:" << writefile);
557
558         string const tex_format = flavor2format(runparams.flavor);
559
560         switch (type(params())) {
561         case VERB:
562         case VERBAST: {
563                 incfile = latex_path(incfile);
564                 // FIXME UNICODE
565                 os << '\\' << from_ascii(params().getCmdName()) << '{'
566                    << from_utf8(incfile) << '}';
567                 break;
568         }
569         case INPUT: {
570                 runparams.exportdata->addExternalFile(tex_format, writefile,
571                                                       exportfile);
572
573                 // \input wants file with extension (default is .tex)
574                 if (!isLyXFileName(included_file.absFileName())) {
575                         incfile = latex_path(incfile);
576                         // FIXME UNICODE
577                         os << '\\' << from_ascii(params().getCmdName())
578                            << '{' << from_utf8(incfile) << '}';
579                 } else {
580                         incfile = changeExtension(incfile, ".tex");
581                         incfile = latex_path(incfile);
582                         // FIXME UNICODE
583                         os << '\\' << from_ascii(params().getCmdName())
584                            << '{' << from_utf8(incfile) <<  '}';
585                 }
586                 break;
587         }
588         case LISTINGS: {
589                 runparams.exportdata->addExternalFile(tex_format, writefile,
590                                                       exportfile);
591                 os << '\\' << from_ascii(params().getCmdName());
592                 string const opt = to_utf8(params()["lstparams"]);
593                 // opt is set in QInclude dialog and should have passed validation.
594                 InsetListingsParams params(opt);
595                 if (!params.params().empty())
596                         os << "[" << from_utf8(params.params()) << "]";
597                 os << '{'  << from_utf8(incfile) << '}';
598                 break;
599         }
600         case INCLUDE: {
601                 runparams.exportdata->addExternalFile(tex_format, writefile,
602                                                       exportfile);
603
604                 // \include don't want extension and demands that the
605                 // file really have .tex
606                 incfile = changeExtension(incfile, string());
607                 incfile = latex_path(incfile);
608                 // FIXME UNICODE
609                 os << '\\' << from_ascii(params().getCmdName()) << '{'
610                    << from_utf8(incfile) << '}';
611                 break;
612         }
613         case NONE:
614                 break;
615         }
616
617         if (runparams.inComment || runparams.dryrun)
618                 // Don't try to load or copy the file if we're
619                 // in a comment or doing a dryrun
620                 return;
621
622         if (isInputOrInclude(params()) &&
623                  isLyXFileName(included_file.absFileName())) {
624                 // if it's a LyX file and we're inputting or including,
625                 // try to load it so we can write the associated latex
626
627                 Buffer * tmp = loadIfNeeded();
628                 if (!tmp) {
629                         docstring text = bformat(_("Could not load included "
630                                 "file\n`%1$s'\n"
631                                 "Please, check whether it actually exists."),
632                                 included_file.displayName());
633                         Alert::warning(_("Missing included file"), text);
634                         return;
635                 }
636
637                 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
638                         // FIXME UNICODE
639                         docstring text = bformat(_("Included file `%1$s'\n"
640                                 "has textclass `%2$s'\n"
641                                 "while parent file has textclass `%3$s'."),
642                                 included_file.displayName(),
643                                 from_utf8(tmp->params().documentClass().name()),
644                                 from_utf8(masterBuffer->params().documentClass().name()));
645                         Alert::warning(_("Different textclasses"), text, true);
646                 }
647
648                 // Make sure modules used in child are all included in master
649                 // FIXME It might be worth loading the children's modules into the master
650                 // over in BufferParams rather than doing this check.
651                 LayoutModuleList const masterModules = masterBuffer->params().getModules();
652                 LayoutModuleList const childModules = tmp->params().getModules();
653                 LayoutModuleList::const_iterator it = childModules.begin();
654                 LayoutModuleList::const_iterator end = childModules.end();
655                 for (; it != end; ++it) {
656                         string const module = *it;
657                         LayoutModuleList::const_iterator found =
658                                 find(masterModules.begin(), masterModules.end(), module);
659                         if (found == masterModules.end()) {
660                                 docstring text = bformat(_("Included file `%1$s'\n"
661                                         "uses module `%2$s'\n"
662                                         "which is not used in parent file."),
663                                         included_file.displayName(), from_utf8(module));
664                                 Alert::warning(_("Module not found"), text);
665                         }
666                 }
667
668                 tmp->markDepClean(masterBuffer->temppath());
669
670                 // Don't assume the child's format is latex
671                 string const inc_format = tmp->params().bufferFormat();
672                 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
673                         formats.extension(inc_format)));
674
675                 // FIXME: handle non existing files
676                 // The included file might be written in a different encoding
677                 // and language.
678                 Encoding const * const oldEnc = runparams.encoding;
679                 Language const * const oldLang = runparams.master_language;
680                 // If the master has full unicode flavor (XeTeX, LuaTeX),
681                 // the children must be encoded in plain utf8!
682                 runparams.encoding = runparams.isFullUnicode() ?
683                         encodings.fromLyXName("utf8-plain")
684                         : &tmp->params().encoding();
685                 runparams.master_language = buffer().params().language;
686                 runparams.par_begin = 0;
687                 runparams.par_end = tmp->paragraphs().size();
688                 runparams.is_child = true;
689                 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
690                                 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
691                         docstring msg = bformat(_("Included file `%1$s' "
692                                         "was not exported correctly.\nWarning: "
693                                         "LaTeX export is probably incomplete."),
694                                         included_file.displayName());
695                         ErrorList const & el = tmp->errorList("Export");
696                         if (!el.empty())
697                                 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
698                                                 msg, el.begin()->error,
699                                                 el.begin()->description);
700                         Alert::warning(_("Export failure"), msg);
701                 }
702                 runparams.encoding = oldEnc;
703                 runparams.master_language = oldLang;
704                 runparams.is_child = false;
705
706                 // If needed, use converters to produce a latex file from the child
707                 if (tmpwritefile != writefile) {
708                         ErrorList el;
709                         bool const success =
710                                 theConverters().convert(tmp, tmpwritefile, writefile,
711                                                         included_file,
712                                                         inc_format, tex_format, el);
713
714                         if (!success) {
715                                 docstring msg = bformat(_("Included file `%1$s' "
716                                                 "was not exported correctly.\nWarning: "
717                                                 "LaTeX export is probably incomplete."),
718                                                 included_file.displayName());
719                                 if (!el.empty())
720                                         msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
721                                                         msg, el.begin()->error,
722                                                         el.begin()->description);
723                                 Alert::warning(_("Export failure"), msg);
724                         }
725                 }
726         } else {
727                 // In this case, it's not a LyX file, so we copy the file
728                 // to the temp dir, so that .aux files etc. are not created
729                 // in the original dir. Files included by this file will be
730                 // found via either the environment variable TEXINPUTS, or
731                 // input@path, see ../Buffer.cpp.
732                 unsigned long const checksum_in  = included_file.checksum();
733                 unsigned long const checksum_out = writefile.checksum();
734
735                 if (checksum_in != checksum_out) {
736                         if (!included_file.copyTo(writefile)) {
737                                 // FIXME UNICODE
738                                 LYXERR(Debug::LATEX,
739                                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
740                                                                         "into the temporary directory."),
741                                                          from_utf8(included_file.absFileName()))));
742                                 return;
743                         }
744                 }
745         }
746 }
747
748
749 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
750 {
751         if (rp.inComment)
752                  return docstring();
753
754         // For verbatim and listings, we just include the contents of the file as-is.
755         // In the case of listings, we wrap it in <pre>.
756         bool const listing = isListings(params());
757         if (listing || isVerbatim(params())) {
758                 if (listing)
759                         xs << html::StartTag("pre");
760                 // FIXME: We don't know the encoding of the file, default to UTF-8.
761                 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
762                 if (listing)
763                         xs << html::EndTag("pre");
764                 return docstring();
765         }
766
767         // We don't (yet) know how to Input or Include non-LyX files.
768         // (If we wanted to get really arcane, we could run some tex2html
769         // converter on the included file. But that's just masochistic.)
770         FileName const included_file = includedFileName(buffer(), params());
771         if (!isLyXFileName(included_file.absFileName())) {
772                 frontend::Alert::warning(_("Unsupported Inclusion"),
773                                          bformat(_("LyX does not know how to include non-LyX files when "
774                                                    "generating HTML output. Offending file:\n%1$s"),
775                                                     params()["filename"]));
776                 return docstring();
777         }
778
779         // In the other cases, we will generate the HTML and include it.
780
781         // Check we're not trying to include ourselves.
782         // FIXME RECURSIVE INCLUDE
783         if (buffer().absFileName() == included_file.absFileName()) {
784                 Alert::error(_("Recursive input"),
785                                bformat(_("Attempted to include file %1$s in itself! "
786                                "Ignoring inclusion."), params()["filename"]));
787                 return docstring();
788         }
789
790         Buffer const * const ibuf = loadIfNeeded();
791         if (!ibuf)
792                 return docstring();
793
794         // are we generating only some paragraphs, or all of them?
795         bool const all_pars = !rp.dryrun || 
796                         (rp.par_begin == 0 && 
797                          rp.par_end == (int)buffer().text().paragraphs().size());
798         
799         OutputParams op = rp;
800         if (all_pars) {
801                 op.par_begin = 0;
802                 op.par_end = 0;
803                 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
804         } else
805                 xs << XHTMLStream::ESCAPE_NONE 
806                    << "<!-- Included file: " 
807                    << from_utf8(included_file.absFileName()) 
808                    << XHTMLStream::ESCAPE_NONE 
809                          << " -->";
810         return docstring();
811 }
812
813
814 int InsetInclude::plaintext(odocstringstream & os,
815         OutputParams const & op, size_t) const
816 {
817         // just write the filename if we're making a tooltip or toc entry,
818         // or are generating this for advanced search
819         if (op.for_tooltip || op.for_toc || op.for_search) {
820                 os << '[' << screenLabel() << '\n'
821                    << getParam("filename") << "\n]";
822                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
823         }
824
825         if (isVerbatim(params()) || isListings(params())) {
826                 os << '[' << screenLabel() << '\n'
827                    // FIXME: We don't know the encoding of the file, default to UTF-8.
828                    << includedFileName(buffer(), params()).fileContents("UTF-8")
829                    << "\n]";
830                 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
831         }
832
833         Buffer const * const ibuf = loadIfNeeded();
834         if (!ibuf) {
835                 docstring const str = '[' + screenLabel() + ']';
836                 os << str;
837                 return str.size();
838         }
839         writePlaintextFile(*ibuf, os, op);
840         return 0;
841 }
842
843
844 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
845 {
846         string incfile = to_utf8(params()["filename"]);
847
848         // Do nothing if no file name has been specified
849         if (incfile.empty())
850                 return 0;
851
852         string const included_file = includedFileName(buffer(), params()).absFileName();
853
854         // Check we're not trying to include ourselves.
855         // FIXME RECURSIVE INCLUDE
856         // This isn't sufficient, as the inclusion could be downstream.
857         // But it'll have to do for now.
858         if (buffer().absFileName() == included_file) {
859                 Alert::error(_("Recursive input"),
860                                bformat(_("Attempted to include file %1$s in itself! "
861                                "Ignoring inclusion."), from_utf8(incfile)));
862                 return 0;
863         }
864
865         string exppath = incfile;
866         if (!runparams.export_folder.empty()) {
867                 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
868                 FileName(exppath).onlyPath().createPath();
869         }
870
871         // write it to a file (so far the complete file)
872         string const exportfile = changeExtension(exppath, ".sgml");
873         DocFileName writefile(changeExtension(included_file, ".sgml"));
874
875         Buffer * tmp = loadIfNeeded();
876         if (tmp) {
877                 string const mangled = writefile.mangledFileName();
878                 writefile = makeAbsPath(mangled,
879                                         buffer().masterBuffer()->temppath());
880                 if (!runparams.nice)
881                         incfile = mangled;
882
883                 LYXERR(Debug::LATEX, "incfile:" << incfile);
884                 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
885                 LYXERR(Debug::LATEX, "writefile:" << writefile);
886
887                 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
888         }
889
890         runparams.exportdata->addExternalFile("docbook", writefile,
891                                               exportfile);
892         runparams.exportdata->addExternalFile("docbook-xml", writefile,
893                                               exportfile);
894
895         if (isVerbatim(params()) || isListings(params())) {
896                 os << "<inlinegraphic fileref=\""
897                    << '&' << include_label << ';'
898                    << "\" format=\"linespecific\">";
899         } else
900                 os << '&' << include_label << ';';
901
902         return 0;
903 }
904
905
906 void InsetInclude::validate(LaTeXFeatures & features) const
907 {
908         LATTEST(&buffer() == &features.buffer());
909
910         string incfile = to_utf8(params()["filename"]);
911         string const included_file =
912                 includedFileName(buffer(), params()).absFileName();
913
914         string writefile;
915         if (isLyXFileName(included_file))
916                 writefile = changeExtension(included_file, ".sgml");
917         else
918                 writefile = included_file;
919
920         if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
921                 incfile = DocFileName(writefile).mangledFileName();
922                 writefile = makeAbsPath(incfile,
923                                         buffer().masterBuffer()->temppath()).absFileName();
924         }
925
926         features.includeFile(include_label, writefile);
927
928         features.useInsetLayout(getLayout());
929         if (isVerbatim(params()))
930                 features.require("verbatim");
931         else if (isListings(params()))
932                 features.require("listings");
933
934         // Here we must do the fun stuff...
935         // Load the file in the include if it needs
936         // to be loaded:
937         Buffer * const tmp = loadIfNeeded();
938         if (tmp) {
939                 // the file is loaded
940                 // make sure the buffer isn't us
941                 // FIXME RECURSIVE INCLUDES
942                 // This is not sufficient, as recursive includes could be
943                 // more than a file away. But it will do for now.
944                 if (tmp && tmp != &buffer()) {
945                         // We must temporarily change features.buffer,
946                         // otherwise it would always be the master buffer,
947                         // and nested includes would not work.
948                         features.setBuffer(*tmp);
949                         // Maybe this is already a child
950                         bool const is_child =
951                                 features.runparams().is_child;
952                         features.runparams().is_child = true;
953                         tmp->validate(features);
954                         features.runparams().is_child = is_child;
955                         features.setBuffer(buffer());
956                 }
957         }
958 }
959
960
961 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
962 {
963         Buffer * child = loadIfNeeded();
964         if (!child)
965                 return;
966         child->collectBibKeys();
967 }
968
969
970 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
971 {
972         LBUFERR(mi.base.bv);
973
974         bool use_preview = false;
975         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
976                 graphics::PreviewImage const * pimage =
977                         preview_->getPreviewImage(mi.base.bv->buffer());
978                 use_preview = pimage && pimage->image();
979         }
980
981         if (use_preview) {
982                 preview_->metrics(mi, dim);
983         } else {
984                 if (!set_label_) {
985                         set_label_ = true;
986                         button_.update(screenLabel(), true);
987                 }
988                 button_.metrics(mi, dim);
989         }
990
991         Box b(0, dim.wid, -dim.asc, dim.des);
992         button_.setBox(b);
993 }
994
995
996 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
997 {
998         LBUFERR(pi.base.bv);
999
1000         bool use_preview = false;
1001         if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
1002                 graphics::PreviewImage const * pimage =
1003                         preview_->getPreviewImage(pi.base.bv->buffer());
1004                 use_preview = pimage && pimage->image();
1005         }
1006
1007         if (use_preview)
1008                 preview_->draw(pi, x, y);
1009         else
1010                 button_.draw(pi, x, y);
1011 }
1012
1013
1014 string InsetInclude::contextMenuName() const
1015 {
1016         return "context-include";
1017 }
1018
1019
1020 Inset::DisplayType InsetInclude::display() const
1021 {
1022         return type(params()) == INPUT ? Inline : AlignCenter;
1023 }
1024
1025
1026 docstring InsetInclude::layoutName() const
1027 {
1028         if (isListings(params()))
1029                 return from_ascii("IncludeListings");
1030         return InsetCommand::layoutName();
1031 }
1032
1033
1034 //
1035 // preview stuff
1036 //
1037
1038 void InsetInclude::fileChanged() const
1039 {
1040         Buffer const * const buffer = updateFrontend();
1041         if (!buffer)
1042                 return;
1043
1044         preview_->removePreview(*buffer);
1045         add_preview(*preview_.get(), *this, *buffer);
1046         preview_->startLoading(*buffer);
1047 }
1048
1049
1050 namespace {
1051
1052 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1053 {
1054         FileName const included_file = includedFileName(buffer, params);
1055
1056         return type(params) == INPUT && params.preview() &&
1057                 included_file.isReadableFile();
1058 }
1059
1060
1061 docstring latexString(InsetInclude const & inset)
1062 {
1063         TexRow texrow;
1064         odocstringstream ods;
1065         otexstream os(ods, texrow);
1066         // We don't need to set runparams.encoding since this will be done
1067         // by latex() anyway.
1068         OutputParams runparams(0);
1069         runparams.flavor = OutputParams::LATEX;
1070         inset.latex(os, runparams);
1071
1072         return ods.str();
1073 }
1074
1075
1076 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1077                  Buffer const & buffer)
1078 {
1079         InsetCommandParams const & params = inset.params();
1080         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
1081             preview_wanted(params, buffer)) {
1082                 renderer.setAbsFile(includedFileName(buffer, params));
1083                 docstring const snippet = latexString(inset);
1084                 renderer.addPreview(snippet, buffer);
1085         }
1086 }
1087
1088 } // namespace anon
1089
1090
1091 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1092         graphics::PreviewLoader & ploader) const
1093 {
1094         Buffer const & buffer = ploader.buffer();
1095         if (!preview_wanted(params(), buffer))
1096                 return;
1097         preview_->setAbsFile(includedFileName(buffer, params()));
1098         docstring const snippet = latexString(*this);
1099         preview_->addPreview(snippet, ploader);
1100 }
1101
1102
1103 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active) const
1104 {
1105         TocBackend & backend = buffer().tocBackend();
1106
1107         if (isListings(params())) {
1108                 if (label_)
1109                         label_->addToToc(cpit, output_active);
1110
1111                 InsetListingsParams p(to_utf8(params()["lstparams"]));
1112                 string caption = p.getParamValue("caption");
1113                 if (caption.empty())
1114                         return;
1115                 Toc & toc = backend.toc("listing");
1116                 docstring str = convert<docstring>(toc.size() + 1)
1117                         + ". " +  from_utf8(caption);
1118                 DocIterator pit = cpit;
1119                 toc.push_back(TocItem(pit, 0, str, output_active));
1120                 return;
1121         }
1122         Buffer const * const childbuffer = getChildBuffer();
1123         if (!childbuffer)
1124                 return;
1125
1126         Toc & toc = backend.toc("child");
1127         docstring str = childbuffer->fileName().displayName();
1128         toc.push_back(TocItem(cpit, 0, str, output_active));
1129
1130         TocList & toclist = backend.tocs();
1131         childbuffer->tocBackend().update(output_active);
1132         TocList const & childtoclist = childbuffer->tocBackend().tocs();
1133         TocList::const_iterator it = childtoclist.begin();
1134         TocList::const_iterator const end = childtoclist.end();
1135         for(; it != end; ++it)
1136                 toclist[it->first].insert(toclist[it->first].end(),
1137                         it->second.begin(), it->second.end());
1138 }
1139
1140
1141 void InsetInclude::updateCommand()
1142 {
1143         if (!label_)
1144                 return;
1145
1146         docstring old_label = label_->getParam("name");
1147         label_->updateLabel(old_label);
1148         // the label might have been adapted (duplicate)
1149         docstring new_label = label_->getParam("name");
1150         if (old_label == new_label)
1151                 return;
1152
1153         // update listings parameters...
1154         InsetCommandParams p(INCLUDE_CODE);
1155         p = params();
1156         InsetListingsParams par(to_utf8(params()["lstparams"]));
1157         par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1158         p["lstparams"] = from_utf8(par.params());
1159         setParams(p);   
1160 }
1161
1162
1163 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1164 {
1165         button_.update(screenLabel(), true);
1166
1167         Buffer const * const childbuffer = getChildBuffer();
1168         if (childbuffer) {
1169                 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1170                 return;
1171         }
1172         if (!isListings(params()))
1173                 return;
1174
1175         if (label_)
1176                 label_->updateBuffer(it, utype);
1177
1178         InsetListingsParams const par(to_utf8(params()["lstparams"]));
1179         if (par.getParamValue("caption").empty()) {
1180                 listings_label_ = buffer().B_("Program Listing");
1181                 return;
1182         }
1183         Buffer const & master = *buffer().masterBuffer();
1184         Counters & counters = master.params().documentClass().counters();
1185         docstring const cnt = from_ascii("listing");
1186         listings_label_ = master.B_("Program Listing");
1187         if (counters.hasCounter(cnt)) {
1188                 counters.step(cnt, utype);
1189                 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1190         }
1191 }
1192
1193
1194 } // namespace lyx