]> git.lyx.org Git - lyx.git/blob - src/insets/InsetExternal.cpp
9da0d772e743a9ec36aee286e793e759f70168e2
[lyx.git] / src / insets / InsetExternal.cpp
1 /**
2  * \file InsetExternal.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup Nielsen
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetExternal.h"
14 #include "insets/ExternalSupport.h"
15 #include "insets/ExternalTemplate.h"
16 #include "insets/RenderButton.h"
17 #include "insets/RenderGraphic.h"
18 #include "insets/RenderPreview.h"
19
20 #include "Buffer.h"
21 #include "Cursor.h"
22 #include "support/debug.h"
23 #include "DispatchResult.h"
24 #include "Exporter.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "support/gettext.h"
28 #include "LaTeXFeatures.h"
29 #include "Lexer.h"
30 #include "LyXRC.h"
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
33
34 #include "frontends/alert.h"
35
36 #include "graphics/PreviewLoader.h"
37
38 #include "support/ExceptionMessage.h"
39 #include "support/filetools.h"
40 #include "support/lstrings.h"
41 #include "support/lyxlib.h"
42 #include "support/convert.h"
43 #include "support/Translator.h"
44
45 #include <boost/bind.hpp>
46
47 #include <sstream>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace {
53
54 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
55
56 unsigned int const defaultLyxScale = 100;
57
58 string defaultTemplateName;
59
60 } // namespace anon
61
62
63 namespace lyx {
64
65 namespace Alert = frontend::Alert;
66
67 extern bool use_gui;
68
69 namespace external {
70
71 TempName::TempName()
72 {
73         FileName const tempname = FileName::tempName("lyxext");
74         // FIXME: This is unsafe
75         tempname.removeFile();
76         // must have an extension for the converter code to work correctly.
77         tempname_ = FileName(tempname.absFilename() + ".tmp");
78 }
79
80
81 TempName::TempName(TempName const &)
82 {
83         tempname_ = TempName()();
84 }
85
86
87 TempName::~TempName()
88 {
89         tempname_.removeFile();
90 }
91
92
93 TempName & TempName::operator=(TempName const & other)
94 {
95         if (this != &other)
96                 tempname_ = TempName()();
97         return *this;
98 }
99
100
101 namespace {
102
103 /// The translator between the Display enum and corresponding lyx string.
104 Translator<DisplayType, string> const initTranslator()
105 {
106         Translator<DisplayType, string> translator(DefaultDisplay, "default");
107
108         // Fill the display translator
109         translator.addPair(MonochromeDisplay, "monochrome");
110         translator.addPair(GrayscaleDisplay, "grayscale");
111         translator.addPair(ColorDisplay, "color");
112         translator.addPair(PreviewDisplay, "preview");
113         translator.addPair(NoDisplay, "none");
114
115         return translator;
116 }
117
118 } // namespace anon
119
120
121 Translator<DisplayType, string> const & displayTranslator()
122 {
123         static Translator<DisplayType, string> const translator =
124                 initTranslator();
125         return translator;
126 }
127
128 } // namespace external
129
130
131 InsetExternalParams::InsetExternalParams()
132         : display(defaultDisplayType),
133           lyxscale(defaultLyxScale),
134           draft(false)
135 {
136         if (defaultTemplateName.empty()) {
137                 external::TemplateManager const & etm =
138                         external::TemplateManager::get();
139                 templatename_ = etm.getTemplates().begin()->first;
140         } else
141                 templatename_ = defaultTemplateName;
142 }
143
144
145 namespace {
146
147 template <typename T>
148 void clearIfNotFound(T & data, external::TransformID value,
149                      vector<external::TransformID> const & ids)
150 {
151         typedef vector<external::TransformID>::const_iterator
152                 const_iterator;
153
154         const_iterator it  = ids.begin();
155         const_iterator end = ids.end();
156         it = find(it, end, value);
157         if (it == end)
158                 data = T();
159 }
160
161 } // namespace anon
162
163
164 void InsetExternalParams::settemplate(string const & name)
165 {
166         templatename_ = name;
167
168         external::TemplateManager const & etm =
169                 external::TemplateManager::get();
170         external::Template const * const et = etm.getTemplateByName(name);
171         if (!et)
172                 // Be safe. Don't lose data.
173                 return;
174
175         // Ascertain which transforms the template supports.
176         // Empty all those that it doesn't.
177         vector<external::TransformID> const & ids = et->transformIds;
178         clearIfNotFound(clipdata,     external::Clip,   ids);
179         clearIfNotFound(extradata,    external::Extra,  ids);
180         clearIfNotFound(resizedata,   external::Resize, ids);
181         clearIfNotFound(rotationdata, external::Rotate, ids);
182 }
183
184
185 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
186 {
187         os << "External\n"
188            << "\ttemplate " << templatename() << '\n';
189
190         if (!filename.empty()) {
191                 os << "\tfilename " << filename.outputFilename(buffer.filePath()) << '\n';
192                 os << "\tembed " << (filename.embedded() ? filename.inzipName() : "\"\"") << '\n';
193         }
194         if (display != defaultDisplayType)
195                 os << "\tdisplay "
196                    << external::displayTranslator().find(display)
197                    << '\n';
198
199         if (lyxscale != defaultLyxScale)
200                 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
201
202         if (draft)
203                 os << "\tdraft\n";
204
205         if (!clipdata.bbox.empty())
206                 os << "\tboundingBox " << clipdata.bbox << '\n';
207         if (clipdata.clip)
208                 os << "\tclip\n";
209
210         external::ExtraData::const_iterator it  = extradata.begin();
211         external::ExtraData::const_iterator end = extradata.end();
212         for (; it != end; ++it) {
213                 if (!it->second.empty())
214                         os << "\textra " << it->first << " \""
215                            << it->second << "\"\n";
216         }
217
218         if (!rotationdata.no_rotation()) {
219                 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
220                 if (rotationdata.origin() != external::RotationData::DEFAULT)
221                         os << "\trotateOrigin "
222                            << rotationdata.originString() << '\n';
223         }
224
225         if (!resizedata.no_resize()) {
226                 double const scl = convert<double>(resizedata.scale);
227                 if (!float_equal(scl, 0.0, 0.05)) {
228                         if (!float_equal(scl, 100.0, 0.05))
229                                 os << "\tscale "
230                                    << resizedata.scale << '\n';
231                 } else {
232                         if (!resizedata.width.zero())
233                                 os << "\twidth "
234                                    << resizedata.width.asString() << '\n';
235                         if (!resizedata.height.zero())
236                                 os << "\theight "
237                                    << resizedata.height.asString() << '\n';
238                 }
239                 if (resizedata.keepAspectRatio)
240                         os << "\tkeepAspectRatio\n";
241         }
242 }
243
244
245 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
246 {
247         enum ExternalTags {
248                 EX_TEMPLATE = 1,
249                 EX_FILENAME,
250                 EX_EMBED,
251                 EX_DISPLAY,
252                 EX_LYXSCALE,
253                 EX_DRAFT,
254                 EX_BOUNDINGBOX,
255                 EX_CLIP,
256                 EX_EXTRA,
257                 EX_HEIGHT,
258                 EX_KEEPASPECTRATIO,
259                 EX_ROTATEANGLE,
260                 EX_ROTATEORIGIN,
261                 EX_SCALE,
262                 EX_WIDTH,
263                 EX_END
264         };
265
266         keyword_item external_tags[] = {
267                 { "\\end_inset",     EX_END },
268                 { "boundingBox",     EX_BOUNDINGBOX },
269                 { "clip",            EX_CLIP },
270                 { "display",         EX_DISPLAY},
271                 { "draft",           EX_DRAFT},
272                 { "extra",           EX_EXTRA },
273                 { "filename",        EX_FILENAME},
274                 { "embed",           EX_EMBED},
275                 { "height",          EX_HEIGHT },
276                 { "keepAspectRatio", EX_KEEPASPECTRATIO },
277                 { "lyxscale",        EX_LYXSCALE},
278                 { "rotateAngle",     EX_ROTATEANGLE },
279                 { "rotateOrigin",    EX_ROTATEORIGIN },
280                 { "scale",           EX_SCALE },
281                 { "template",        EX_TEMPLATE },
282                 { "width",           EX_WIDTH }
283         };
284
285         PushPopHelper pph(lex, external_tags, EX_END);
286
287         bool found_end  = false;
288         bool read_error = false;
289
290         while (lex.isOK()) {
291                 switch (lex.lex()) {
292                 case EX_TEMPLATE:
293                         lex.next();
294                         templatename_ = lex.getString();
295                         break;
296
297                 case EX_FILENAME: {
298                         lex.eatLine();
299                         string const name = lex.getString();
300                         filename.set(name, buffer.filePath());
301                         break;
302                 }
303                 
304                 case EX_EMBED: {
305                         lex.next();
306                         string const name = lex.getString();
307                         filename.setInzipName(name);
308                         filename.setEmbed(!name.empty());
309                         break;
310                 }
311
312                 case EX_DISPLAY: {
313                         lex.next();
314                         string const name = lex.getString();
315                         display = external::displayTranslator().find(name);
316                         break;
317                 }
318
319                 case EX_LYXSCALE:
320                         lex.next();
321                         lyxscale = lex.getInteger();
322                         break;
323
324                 case EX_DRAFT:
325                         draft = true;
326                         break;
327
328                 case EX_BOUNDINGBOX:
329                         lex.next();
330                         clipdata.bbox.xl = lex.getInteger();
331                         lex.next();
332                         clipdata.bbox.yb = lex.getInteger();
333                         lex.next();
334                         clipdata.bbox.xr = lex.getInteger();
335                         lex.next();
336                         clipdata.bbox.yt = lex.getInteger();
337                         break;
338
339                 case EX_CLIP:
340                         clipdata.clip = true;
341                         break;
342
343                 case EX_EXTRA: {
344                         lex.next();
345                         string const name = lex.getString();
346                         lex.next();
347                         extradata.set(name, lex.getString());
348                         break;
349                 }
350
351                 case EX_HEIGHT:
352                         lex.next();
353                         resizedata.height = Length(lex.getString());
354                         break;
355
356                 case EX_KEEPASPECTRATIO:
357                         resizedata.keepAspectRatio = true;
358                         break;
359
360                 case EX_ROTATEANGLE:
361                         lex.next();
362                         rotationdata.angle = lex.getString();
363                         break;
364
365                 case EX_ROTATEORIGIN:
366                         lex.next();
367                         rotationdata.origin(lex.getString());
368                         break;
369
370                 case EX_SCALE:
371                         lex.next();
372                         resizedata.scale = lex.getString();
373                         break;
374
375                 case EX_WIDTH:
376                         lex.next();
377                         resizedata.width = Length(lex.getString());
378                         break;
379
380                 case EX_END:
381                         found_end = true;
382                         break;
383
384                 default:
385                         lex.printError("ExternalInset::read: Wrong tag: $$Token");
386                         read_error = true;
387                         break;
388                 }
389
390                 if (found_end || read_error)
391                         break;
392         }
393
394         if (!found_end)
395                 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
396
397         // This is a trick to make sure that the data are self-consistent.
398         settemplate(templatename_);
399
400         if (lyxerr.debugging(Debug::EXTERNAL)) {
401                 lyxerr  << "InsetExternalParams::read:\n";
402                 write(buffer, lyxerr);
403         }
404
405         return !read_error;
406 }
407
408
409 InsetExternal::InsetExternal()
410         : renderer_(new RenderButton)
411 {}
412
413
414 InsetExternal::InsetExternal(InsetExternal const & other)
415         : Inset(other),
416           boost::signals::trackable(),
417           params_(other.params_),
418           renderer_(other.renderer_->clone(this))
419 {}
420
421
422 Inset * InsetExternal::clone() const
423 {
424         return new InsetExternal(*this);
425 }
426
427
428 InsetExternal::~InsetExternal()
429 {
430         InsetExternalMailer(*this).hideDialog();
431 }
432
433
434 void InsetExternal::statusChanged() const
435 {
436         updateFrontend();
437 }
438
439
440 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
441 {
442         switch (cmd.action) {
443
444         case LFUN_EXTERNAL_EDIT: {
445                 Buffer const & buffer = cur.buffer();
446                 InsetExternalParams p;
447                 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
448                 external::editExternal(p, buffer);
449                 break;
450         }
451
452         case LFUN_INSET_MODIFY: {
453                 Buffer const & buffer = cur.buffer();
454                 InsetExternalParams p;
455                 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
456                 if (!p.filename.empty()) {
457                         try {
458                                 p.filename.enable(buffer.embedded(), &buffer);
459                         } catch (ExceptionMessage const & message) {
460                                 Alert::error(message.title_, message.details_);
461                                 // do not set parameter if an error happens
462                                 break;
463                         }
464                 }
465                 setParams(p, buffer);
466                 break;
467         }
468
469         case LFUN_INSET_DIALOG_UPDATE:
470                 InsetExternalMailer(*this).updateDialog(&cur.bv());
471                 break;
472
473         case LFUN_MOUSE_RELEASE:
474                 if (!cur.selection())
475                         InsetExternalMailer(*this).showDialog(&cur.bv());
476                 break;
477
478         default:
479                 Inset::doDispatch(cur, cmd);
480         }
481 }
482
483
484 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
485                 FuncStatus & flag) const
486 {
487         switch (cmd.action) {
488
489         case LFUN_EXTERNAL_EDIT:
490         case LFUN_INSET_MODIFY:
491         case LFUN_INSET_DIALOG_UPDATE:
492                 flag.enabled(true);
493                 return true;
494
495         default:
496                 return Inset::getStatus(cur, cmd, flag);
497         }
498 }
499
500
501 void InsetExternal::registerEmbeddedFiles(Buffer const & buffer,
502         EmbeddedFileList & files) const
503 {
504         files.registerFile(params_.filename, this, buffer);
505 }
506
507
508 void InsetExternal::updateEmbeddedFile(Buffer const & buf,
509         EmbeddedFile const & file)
510 {
511         // when embedding is enabled, change of embedding status leads to actions
512         EmbeddedFile temp = file;
513         temp.enable(buf.embedded(), &buf);
514         // this will not be set if an exception is thorwn in enable()
515         params_.filename = temp;
516 }
517
518
519 void InsetExternal::edit(Cursor & cur, bool)
520 {
521         InsetExternalMailer(*this).showDialog(&cur.bv());
522 }
523
524
525 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
526 {
527         renderer_->metrics(mi, dim);
528 }
529
530
531 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
532 {
533         renderer_->draw(pi, x, y);
534 }
535
536
537 namespace {
538
539 enum RenderType {
540         RENDERBUTTON,
541         RENDERGRAPHIC,
542         RENDERPREVIEW
543 };
544
545
546 RenderType getRenderType(InsetExternalParams const & p)
547 {
548         if (!external::getTemplatePtr(p) ||
549             p.filename.empty() ||
550             p.display == external::NoDisplay)
551                 return RENDERBUTTON;
552
553         if (p.display == external::PreviewDisplay) {
554                 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
555                         return RENDERPREVIEW;
556                 return RENDERBUTTON;
557         }
558
559         if (p.display == external::DefaultDisplay &&
560             lyxrc.display_graphics == graphics::NoDisplay)
561                 return RENDERBUTTON;
562         return RENDERGRAPHIC;
563 }
564
565
566 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
567 {
568         graphics::Params gparams;
569
570         gparams.filename = eparams.filename.availableFile();
571         gparams.icon = eparams.filename.embedded() ? "pin.png" : "";
572         gparams.scale = eparams.lyxscale;
573         if (eparams.clipdata.clip)
574                 gparams.bb = eparams.clipdata.bbox;
575         gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
576
577         switch (eparams.display) {
578         case external::DefaultDisplay:
579                 gparams.display = graphics::DefaultDisplay;
580                 break;
581         case external::MonochromeDisplay:
582                 gparams.display = graphics::MonochromeDisplay;
583                 break;
584         case external::GrayscaleDisplay:
585                 gparams.display = graphics::GrayscaleDisplay;
586                 break;
587         case external::ColorDisplay:
588                 gparams.display = graphics::ColorDisplay;
589                 break;
590         case external::NoDisplay:
591                 gparams.display = graphics::NoDisplay;
592                 break;
593         default:
594                 BOOST_ASSERT(false);
595         }
596         if (gparams.display == graphics::DefaultDisplay)
597                 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
598         // Override the above if we're not using a gui
599         if (!use_gui)
600                 gparams.display = graphics::NoDisplay;
601
602         return gparams;
603 }
604
605
606 docstring const getScreenLabel(InsetExternalParams const & params,
607                             Buffer const & buffer)
608 {
609         external::Template const * const ptr =
610                 external::getTemplatePtr(params);
611         if (!ptr)
612                 // FIXME UNICODE
613                 return bformat((_("External template %1$s is not installed")),
614                                         from_utf8(params.templatename()));
615         // FIXME UNICODE
616         docstring gui = _(ptr->guiName);
617         return from_utf8(external::doSubstitution(params, buffer,
618                                 to_utf8(gui), false));
619 }
620
621 void add_preview_and_start_loading(RenderMonitoredPreview &,
622                                    InsetExternal const &,
623                                    Buffer const &);
624
625 } // namespace anon
626
627
628 InsetExternalParams const & InsetExternal::params() const
629 {
630         return params_;
631 }
632
633
634 void InsetExternal::setParams(InsetExternalParams const & p,
635                               Buffer const & buffer)
636 {
637         params_ = p;
638
639         // Subsequent calls to the InsetExternal::Params default constructor
640         // will use this.
641         defaultTemplateName = params_.templatename();
642
643         switch (getRenderType(params_)) {
644         case RENDERBUTTON: {
645                 RenderButton * button_ptr = renderer_->asButton();
646                 if (!button_ptr) {
647                         renderer_.reset(new RenderButton);
648                         button_ptr = renderer_->asButton();
649                 }
650
651                 button_ptr->update(getScreenLabel(params_, buffer), true);
652                 break;
653         }
654
655         case RENDERGRAPHIC: {
656                 RenderGraphic * graphic_ptr = renderer_->asGraphic();
657                 if (!graphic_ptr) {
658                         renderer_.reset(new RenderGraphic(this));
659                         graphic_ptr = renderer_->asGraphic();
660                 }
661
662                 graphic_ptr->update(get_grfx_params(params_));
663
664                 break;
665         }
666
667         case RENDERPREVIEW: {
668                 RenderMonitoredPreview * preview_ptr =
669                         renderer_->asMonitoredPreview();
670                 if (!preview_ptr) {
671                         renderer_.reset(new RenderMonitoredPreview(this));
672                         preview_ptr = renderer_->asMonitoredPreview();
673                         preview_ptr->fileChanged(
674                                 boost::bind(&InsetExternal::fileChanged, this));
675                 }
676
677                 if (preview_ptr->monitoring())
678                         preview_ptr->stopMonitoring();
679                 add_preview_and_start_loading(*preview_ptr, *this, buffer);
680
681                 break;
682         }
683         }
684 }
685
686
687 void InsetExternal::fileChanged() const
688 {
689         Buffer const * const buffer = updateFrontend();
690         if (!buffer)
691                 return;
692
693         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
694         BOOST_ASSERT(ptr);
695
696         ptr->removePreview(*buffer);
697         add_preview_and_start_loading(*ptr, *this, *buffer);
698 }
699
700
701 void InsetExternal::write(Buffer const & buffer, ostream & os) const
702 {
703         params_.write(buffer, os);
704 }
705
706
707 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
708 {
709         InsetExternalParams params;
710         if (params.read(buffer, lex)) {
711                 // exception handling is not needed as long as embedded files are in place.
712                 params.filename.enable(buffer.embedded(), & buffer);
713                 setParams(params, buffer);
714         }
715 }
716
717
718 int InsetExternal::latex(Buffer const & buf, odocstream & os,
719                          OutputParams const & runparams) const
720 {
721         if (params_.draft) {
722                 // FIXME UNICODE
723                 os << "\\fbox{\\ttfamily{}"
724                    << from_utf8(params_.filename.outputFilename(buf.filePath()))
725                    << "}\n";
726                 return 1;
727         }
728
729         // "nice" means that the buffer is exported to LaTeX format but not
730         // run through the LaTeX compiler.
731         // If we're running through the LaTeX compiler, we should write the
732         // generated files in the buffer's temporary directory.
733         bool const external_in_tmpdir = !runparams.nice;
734         bool const dryrun = runparams.dryrun || runparams.inComment;
735
736         // If the template has specified a PDFLaTeX output, then we try and
737         // use that.
738         if (runparams.flavor == OutputParams::PDFLATEX) {
739                 external::Template const * const et_ptr =
740                         external::getTemplatePtr(params_);
741                 if (!et_ptr)
742                         return 0;
743                 external::Template const & et = *et_ptr;
744
745                 external::Template::Formats::const_iterator cit =
746                         et.formats.find("PDFLaTeX");
747
748                 if (cit != et.formats.end()) {
749                         return external::writeExternal(params_, "PDFLaTeX",
750                                                        buf, os,
751                                                        *(runparams.exportdata),
752                                                        external_in_tmpdir,
753                                                        dryrun);
754                 }
755         }
756
757         return external::writeExternal(params_, "LaTeX", buf, os,
758                                        *(runparams.exportdata),
759                                        external_in_tmpdir,
760                                        dryrun);
761 }
762
763
764 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
765                              OutputParams const & runparams) const
766 {
767         os << '\n'; // output external material on a new line
768         external::writeExternal(params_, "Ascii", buf, os,
769                                 *(runparams.exportdata), false,
770                                 runparams.dryrun || runparams.inComment);
771         return PLAINTEXT_NEWLINE;
772 }
773
774
775 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
776                            OutputParams const & runparams) const
777 {
778         return external::writeExternal(params_, "DocBook", buf, os,
779                                        *(runparams.exportdata), false,
780                                        runparams.dryrun || runparams.inComment);
781 }
782
783
784 void InsetExternal::validate(LaTeXFeatures & features) const
785 {
786         if (params_.draft)
787                 return;
788
789         external::Template const * const et_ptr =
790                 external::getTemplatePtr(params_);
791         if (!et_ptr)
792                 return;
793         external::Template const & et = *et_ptr;
794
795         string format;
796         switch (features.runparams().flavor) {
797         case OutputParams::LATEX:
798                 format = "LaTeX";
799                 break;
800         case OutputParams::PDFLATEX:
801                 format = "PDFLaTeX";
802                 break;
803         case OutputParams::XML:
804                 format = "DocBook";
805                 break;
806         }
807         external::Template::Formats::const_iterator cit =
808                 et.formats.find(format);
809         if (cit == et.formats.end())
810                 return;
811
812         // FIXME: We don't need that always
813         features.require("lyxdot");
814
815         vector<string>::const_iterator it  = cit->second.requirements.begin();
816         vector<string>::const_iterator end = cit->second.requirements.end();
817         for (; it != end; ++it)
818                 features.require(*it);
819
820         external::TemplateManager & etm = external::TemplateManager::get();
821
822         it  = cit->second.preambleNames.begin();
823         end = cit->second.preambleNames.end();
824         for (; it != end; ++it) {
825                 string const preamble = etm.getPreambleDefByName(*it);
826                 if (!preamble.empty())
827                         features.addPreambleSnippet(preamble);
828         }
829 }
830
831
832 //
833 // preview stuff
834 //
835
836 namespace {
837
838 bool preview_wanted(InsetExternalParams const & params)
839 {
840         return params.display == external::PreviewDisplay &&
841                 params.filename.isReadableFile();
842 }
843
844
845 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
846 {
847         odocstringstream os;
848         // We don't need to set runparams.encoding since it is not used by
849         // latex().
850         OutputParams runparams(0);
851         runparams.flavor = OutputParams::LATEX;
852         inset.latex(buffer, os, runparams);
853         return os.str();
854 }
855
856
857 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
858                                    InsetExternal const & inset,
859                                    Buffer const & buffer)
860 {
861         InsetExternalParams const & params = inset.params();
862
863         if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
864             preview_wanted(params)) {
865                 renderer.setAbsFile(params.filename);
866                 docstring const snippet = latex_string(inset, buffer);
867                 renderer.addPreview(snippet, buffer);
868                 renderer.startLoading(buffer);
869         }
870 }
871
872 } // namespace anon
873
874
875 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
876 {
877         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
878         if (!ptr)
879                 return;
880
881         if (preview_wanted(params())) {
882                 ptr->setAbsFile(params_.filename);
883                 docstring const snippet = latex_string(*this, ploader.buffer());
884                 ptr->addPreview(snippet, ploader);
885         }
886 }
887
888
889 /// Mailer stuff
890
891 string const InsetExternalMailer::name_("external");
892
893 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
894         : inset_(inset)
895 {}
896
897
898 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
899 {
900         return params2string(inset_.params(), buffer);
901 }
902
903
904 void InsetExternalMailer::string2params(string const & in,
905                                         Buffer const & buffer,
906                                         InsetExternalParams & params)
907 {
908         params = InsetExternalParams();
909         if (in.empty())
910                 return;
911
912         istringstream data(in);
913         Lexer lex(0,0);
914         lex.setStream(data);
915
916         string name;
917         lex >> name;
918         if (!lex || name != name_)
919                 return print_mailer_error("InsetExternalMailer", in, 1, name_);
920
921         // This is part of the inset proper that is usually swallowed
922         // by Text::readInset
923         string id;
924         lex >> id;
925         if (!lex || id != "External")
926                 return print_mailer_error("InsetBoxMailer", in, 2, "External");
927
928         params.read(buffer, lex);
929 }
930
931
932 string const
933 InsetExternalMailer::params2string(InsetExternalParams const & params,
934                                    Buffer const & buffer)
935 {
936         ostringstream data;
937         data << name_ << ' ';
938         params.write(buffer, data);
939         data << "\\end_inset\n";
940         return data.str();
941 }
942
943 } // namespace lyx