]> git.lyx.org Git - lyx.git/blob - src/insets/InsetExternal.cpp
As observed on users list it's hard to guess where to setup external editor.
[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 "Converter.h"
22 #include "Cursor.h"
23 #include "DispatchResult.h"
24 #include "Exporter.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "LaTeXFeatures.h"
28 #include "Lexer.h"
29 #include "LyX.h" // use_gui
30 #include "LyXRC.h"
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
33 #include "output_latex.h"
34 #include "output_xhtml.h"
35 #include "texstream.h"
36 #include "TocBackend.h"
37
38 #include "frontends/alert.h"
39 #include "frontends/Application.h"
40
41 #include "graphics/PreviewLoader.h"
42
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
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
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
419
420
421 InsetExternal::InsetExternal(Buffer * buf)
422         : Inset(buf), renderer_(new RenderButton)
423 {
424 }
425
426
427 // Mouse hover is not copied and remains empty
428 InsetExternal::InsetExternal(InsetExternal const & other)
429         : Inset(other),
430           params_(other.params_),
431           renderer_(other.renderer_->clone(this))
432 {}
433
434
435 InsetExternal::~InsetExternal()
436 {
437         hideDialogs("external", this);
438
439         map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
440         map<BufferView const *, bool>::iterator end = mouse_hover_.end();
441         for (; it != end; ++it)
442                 if (it->second)
443                         it->first->clearLastInset(this);
444 }
445
446
447 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
448 {
449         mouse_hover_[bv] = mouse_hover;
450         return true;
451 }
452
453
454 void InsetExternal::statusChanged() const
455 {
456         updateFrontend();
457 }
458
459
460 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
461 {
462         switch (cmd.action()) {
463
464         case LFUN_INSET_EDIT: {
465                 InsetExternalParams p =  params();
466                 if (!cmd.argument().empty())
467                         string2params(to_utf8(cmd.argument()), buffer(), p);
468                 external::editExternal(p, buffer());
469                 break;
470         }
471
472         case LFUN_INSET_MODIFY: {
473                 InsetExternalParams p;
474                 string2params(to_utf8(cmd.argument()), buffer(), p);
475                 cur.recordUndo();
476                 setParams(p);
477                 break;
478         }
479
480         case LFUN_INSET_DIALOG_UPDATE:
481                 cur.bv().updateDialog("external",
482                         params2string(params(), cur.bv().buffer()));
483                 break;
484
485         default:
486                 Inset::doDispatch(cur, cmd);
487         }
488 }
489
490
491 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
492                 FuncStatus & flag) const
493 {
494         switch (cmd.action()) {
495
496         case LFUN_INSET_EDIT:
497         case LFUN_INSET_MODIFY:
498         case LFUN_INSET_DIALOG_UPDATE:
499                 flag.setEnabled(true);
500                 return true;
501
502         default:
503                 return Inset::getStatus(cur, cmd, flag);
504         }
505 }
506
507
508 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
509                                                          UpdateType, TocBackend & backend) const
510 {
511         docstring str = screenLabel(params_, buffer());
512         TocBuilder & b = backend.builder("external");
513         b.pushItem(cpit, str, output_active);
514         b.pop();
515 }
516
517
518 bool InsetExternal::showInsetDialog(BufferView * bv) const
519 {
520         bv->showDialog("external", params2string(params(), bv->buffer()),
521                 const_cast<InsetExternal *>(this));
522         return true;
523 }
524
525
526 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
527 {
528         if (!isRendererValid())
529                 updatePreview();
530
531         renderer_->metrics(mi, dim);
532 }
533
534
535 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
536 {
537         if (!isRendererValid())
538                 updatePreview();
539
540         if (renderer_->asButton())
541                 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
542         renderer_->draw(pi, x, y);
543 }
544
545
546 namespace {
547
548 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
549 {
550         graphics::Params gparams;
551
552         gparams.filename = eparams.filename;
553         gparams.scale = eparams.lyxscale;
554         if (eparams.clipdata.clip)
555                 gparams.bb = eparams.clipdata.bbox;
556         gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
557         gparams.display = eparams.display;
558
559         return gparams;
560 }
561
562 } // namespace
563
564
565 static bool isPreviewWanted(InsetExternalParams const & params)
566 {
567         return params.display && params.filename.isReadableFile();
568 }
569
570
571 static docstring latexString(InsetExternal const & inset)
572 {
573         odocstringstream ods;
574         otexstream os(ods);
575         // We don't need to set runparams.encoding since it is not used by
576         // latex().
577         OutputParams runparams(0);
578         runparams.flavor = OutputParams::LATEX;
579         inset.latex(os, runparams);
580         return ods.str();
581 }
582
583
584 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
585                                    InsetExternal const & inset,
586                                    Buffer const & buffer)
587 {
588         InsetExternalParams const & params = inset.params();
589
590         if (RenderPreview::previewText() && isPreviewWanted(params)) {
591                 renderer.setAbsFile(params.filename);
592                 docstring const snippet = latexString(inset);
593                 renderer.addPreview(snippet, buffer);
594                 renderer.startLoading(buffer);
595         }
596 }
597
598
599 InsetExternalParams const & InsetExternal::params() const
600 {
601         return params_;
602 }
603
604
605 bool InsetExternal::isPreviewed() const
606 {
607         return (external::getTemplatePtr(params_) && !params_.filename.empty()
608                 && params_.display
609                 && lyxrc.display_graphics
610                 && params_.preview_mode != PREVIEW_OFF
611                 && (params_.preview_mode != PREVIEW_INSTANT
612                     || RenderPreview::previewText()));
613 }
614
615
616 bool InsetExternal::isRendererValid() const
617 {
618         if (!renderer_->asButton())
619                 return isPreviewed();
620         return !isPreviewed();
621 }
622
623
624 void InsetExternal::setParams(InsetExternalParams const & p)
625 {
626         params_ = p;
627
628         // Subsequent calls to the InsetExternal::Params default constructor
629         // will use this.
630         defaultTemplateName = params_.templatename();
631
632         updatePreview();
633 }
634
635
636 void InsetExternal::updatePreview() const
637 {
638         if (!isPreviewed()) {
639                 RenderButton * button_ptr = renderer_->asButton();
640                 if (!button_ptr) {
641                         renderer_.reset(new RenderButton);
642                         button_ptr = renderer_->asButton();
643                 }
644                 button_ptr->update(screenLabel(params_, buffer()), true, false);
645                 return;
646         }
647
648         switch (params_.preview_mode) {
649         case PREVIEW_OFF:
650                 // Already taken care of above.
651                 LASSERT(false, return);
652                 break;
653         case PREVIEW_INSTANT: {
654                 renderer_ = make_unique<RenderMonitoredPreview>(this);
655                 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
656                 // This connection is closed at the same time as this is destroyed.
657                 preview_ptr->connect([=]() { fileChanged(); });
658                 add_preview_and_start_loading(*preview_ptr, *this, buffer());
659                 break;
660         }
661         case PREVIEW_GRAPHICS: {
662                 RenderGraphic * graphic_ptr = renderer_->asGraphic();
663                 if (!graphic_ptr) {
664                         renderer_.reset(new RenderGraphic(this));
665                         graphic_ptr = renderer_->asGraphic();
666                 }
667                 graphic_ptr->update(get_grfx_params(params_));
668                 break;
669         }
670         }
671 }
672
673
674 void InsetExternal::fileChanged() const
675 {
676         Buffer const * const buffer = updateFrontend();
677         if (!buffer)
678                 return;
679
680         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
681         LASSERT(ptr, return);
682
683         ptr->removePreview(*buffer);
684         add_preview_and_start_loading(*ptr, *this, *buffer);
685 }
686
687
688 void InsetExternal::write(ostream & os) const
689 {
690         params_.write(buffer(), os);
691 }
692
693
694 void InsetExternal::read(Lexer & lex)
695 {
696         InsetExternalParams params;
697         if (params.read(buffer(), lex))
698                 setParams(params);
699 }
700
701
702 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
703 {
704         if (params_.draft) {
705                 // FIXME UNICODE
706                 os << "\\fbox{\\ttfamily{}"
707                    << from_utf8(params_.filename.outputFileName(buffer().filePath()))
708                    << "}\n";
709                 return;
710         }
711
712         // "nice" means that the buffer is exported to LaTeX format but not
713         // run through the LaTeX compiler.
714         // If we're running through the LaTeX compiler, we should write the
715         // generated files in the buffer's temporary directory.
716         bool const external_in_tmpdir = !runparams.nice;
717         bool const dryrun = runparams.dryrun || runparams.inComment;
718
719         // If the template has specified a PDFLaTeX output, then we try and
720         // use that.
721         if (runparams.flavor == OutputParams::PDFLATEX) {
722                 external::Template const * const et_ptr =
723                         external::getTemplatePtr(params_);
724                 if (!et_ptr)
725                         return;
726                 external::Template const & et = *et_ptr;
727
728                 external::Template::Formats::const_iterator cit =
729                         et.formats.find("PDFLaTeX");
730
731                 if (cit != et.formats.end()) {
732                         external::RetVal retval =
733                                 external::writeExternal(params_, "PDFLaTeX", buffer(), os,
734                                     *(runparams.exportdata), external_in_tmpdir, dryrun);
735                         if (retval == external::KILLED) {
736                                 LYXERR0("External template preparation killed.");
737                                 if (buffer().isClone() && buffer().isExporting())
738                                         throw ConversionException();
739                         }
740                         return;
741                 }
742         }
743
744         external::RetVal retval =
745                 external::writeExternal(params_, "LaTeX", buffer(), os,
746                     *(runparams.exportdata), external_in_tmpdir, dryrun);
747         if (retval == external::KILLED) {
748                 LYXERR0("External template preparation killed.");
749                 if (buffer().isClone() && buffer().isExporting())
750                         throw ConversionException();
751         }
752 }
753
754
755 int InsetExternal::plaintext(odocstringstream & os,
756                              OutputParams const & runparams, size_t) const
757 {
758         // this is too slow for constant use
759         if (runparams.for_tooltip)
760                 return 0;
761
762         bool const external_in_tmpdir = !runparams.nice;
763         bool const dryrun = runparams.dryrun || runparams.inComment;
764         otexstream ots(os);
765         ots << '\n'; // output external material on a new line
766         external::RetVal retval =
767                 external::writeExternal(params_, "Ascii", buffer(), ots,
768                     *(runparams.exportdata), external_in_tmpdir, dryrun);
769         if (retval == external::KILLED) {
770                 LYXERR0("External template preparation killed.");
771                 if (buffer().isClone() && buffer().isExporting())
772                         throw ConversionException();
773         }
774         return PLAINTEXT_NEWLINE;
775 }
776
777
778 int InsetExternal::docbook(odocstream & os,
779                            OutputParams const & runparams) const
780 {
781         bool const external_in_tmpdir = !runparams.nice;
782         bool const dryrun = runparams.dryrun || runparams.inComment;
783         odocstringstream ods;
784         otexstream ots(ods);
785         external::RetVal retval =
786                 external::writeExternal(params_, "DocBook", buffer(), ots,
787                     *(runparams.exportdata), external_in_tmpdir, dryrun);
788         if (retval == external::KILLED) {
789                 LYXERR0("External template preparation killed.");
790                 if (buffer().isClone() && buffer().isExporting())
791                         throw ConversionException();
792         }
793         os << ods.str();
794         return int(count(ods.str().begin(), ods.str().end(), '\n'));
795 }
796
797
798 docstring InsetExternal::xhtml(XHTMLStream & xs,
799                         OutputParams const & runparams) const
800 {
801         bool const external_in_tmpdir = !runparams.nice;
802         bool const dryrun = runparams.dryrun || runparams.inComment;
803         odocstringstream ods;
804         otexstream ots(ods);
805         external::RetVal retval =
806                 external::writeExternal(params_, "XHTML", buffer(), ots,
807                     *(runparams.exportdata), external_in_tmpdir, dryrun);
808         if (retval == external::KILLED) {
809                 LYXERR0("External template preparation killed.");
810                 if (buffer().isClone() && buffer().isExporting())
811                         throw ConversionException();
812         }
813         xs << XHTMLStream::ESCAPE_NONE << ods.str();
814         return docstring();
815 }
816
817
818 void InsetExternal::validate(LaTeXFeatures & features) const
819 {
820         if (params_.draft)
821                 return;
822
823         external::Template const * const et_ptr =
824                 external::getTemplatePtr(params_);
825         if (!et_ptr)
826                 return;
827         external::Template const & et = *et_ptr;
828
829         string format;
830         switch (features.runparams().flavor) {
831         case OutputParams::LATEX:
832         case OutputParams::DVILUATEX:
833                 format = "LaTeX";
834                 break;
835         case OutputParams::LUATEX:
836         case OutputParams::PDFLATEX:
837         case OutputParams::XETEX:
838                 format = "PDFLaTeX";
839                 break;
840         case OutputParams::XML:
841                 format = "DocBook";
842                 break;
843         case OutputParams::HTML:
844                 format = "html";
845                 break;
846         case OutputParams::TEXT:
847                 format = "text";
848                 break;
849         case OutputParams::LYX:
850                 format = "lyx";
851                 break;
852         }
853         external::Template::Formats::const_iterator cit =
854                 et.formats.find(format);
855
856         if (cit == et.formats.end()) {
857                 // If the template has not specified a PDFLaTeX output,
858                 // we try the LaTeX format.
859                 if (format == "PDFLaTeX") {
860                         cit = et.formats.find("LaTeX");
861                         if (cit == et.formats.end())
862                                 return;
863                 } else
864                         return;
865         }
866
867         // FIXME: We don't need that always, see InsetGraphics
868         features.require("lyxdot");
869
870         vector<string>::const_iterator it  = cit->second.requirements.begin();
871         vector<string>::const_iterator end = cit->second.requirements.end();
872         for (; it != end; ++it)
873                 features.require(*it);
874
875         external::TemplateManager & etm = external::TemplateManager::get();
876
877         for (string const & name : cit->second.preambleNames) {
878                 docstring const preamble = etm.getPreambleDefByName(name);
879                 if (!preamble.empty())
880                         features.addPreambleSnippet(preamble);
881         }
882 }
883
884
885 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
886                                graphics::PreviewLoader & ploader) const
887 {
888         RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
889         if (!ptr)
890                 return;
891
892         if (isPreviewWanted(params())) {
893                 ptr->setAbsFile(params_.filename);
894                 docstring const snippet = latexString(*this);
895                 ptr->addPreview(snippet, ploader);
896         }
897 }
898
899
900 string InsetExternal::contextMenuName() const
901 {
902         return "context-external";
903 }
904
905
906 void InsetExternal::string2params(string const & in, Buffer const & buffer,
907         InsetExternalParams & params)
908 {
909         params = InsetExternalParams();
910         if (in.empty())
911                 return;
912
913         istringstream data(in);
914         Lexer lex;
915         lex.setStream(data);
916
917         string name;
918         lex >> name;
919         if (!lex || name != "external") {
920                 LYXERR0("InsetExternal::string2params(" << in << ")\n"
921                                           "Expected arg 1 to be \"external\"\n");
922                 return;
923         }
924
925         // This is part of the inset proper that is usually swallowed
926         // by Text::readInset
927         string id;
928         lex >> id;
929         if (!lex || id != "External") {
930                 LYXERR0("InsetExternal::string2params(" << in << ")\n"
931                                           "Expected arg 2 to be \"External\"\n");
932                 return;
933         }
934
935         params.read(buffer, lex);
936 }
937
938
939 string InsetExternal::params2string(InsetExternalParams const & params,
940         Buffer const & buffer)
941 {
942         ostringstream data;
943         data << "external" << ' ';
944         params.write(buffer, data);
945         data << "\\end_inset\n";
946         return data.str();
947 }
948
949 } // namespace lyx