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