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