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