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