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