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