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