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