]> git.lyx.org Git - lyx.git/blob - src/insets/Inset.h
fca566f29daab1a3b9eecf656fd44ef77ca0f673
[lyx.git] / src / insets / Inset.h
1 // -*- C++ -*-
2 /**
3  * \file Inset.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Alejandro Aguilar Sierra
8  * \author Jürgen Vigna
9  * \author Lars Gullik Bjønnes
10  * \author Matthias Ettrich
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #ifndef INSETBASE_H
16 #define INSETBASE_H
17
18 #include "ColorCode.h"
19 #include "InsetCode.h"
20 #include "Layout.h"
21 #include "OutputEnums.h"
22
23 #include "support/strfwd.h"
24 #include "support/types.h"
25
26
27 namespace lyx {
28
29 class BiblioInfo;
30 class Buffer;
31 class BufferView;
32 class Change;
33 class CompletionList;
34 class Cursor;
35 class CursorSlice;
36 class Dimension;
37 class DocIterator;
38 class FuncRequest;
39 class FuncStatus;
40 class InsetCollapsable;
41 class InsetCommand;
42 class InsetIterator;
43 class InsetLayout;
44 class InsetList;
45 class InsetMath;
46 class InsetTabular;
47 class InsetText;
48 class LaTeXFeatures;
49 class Lexer;
50 class MathAtom;
51 class MetricsInfo;
52 class OutputParams;
53 class PainterInfo;
54 class ParConstIterator;
55 class ParIterator;
56 class Text;
57 class TocList;
58 class XHTMLStream;
59
60 namespace graphics { class PreviewLoader; }
61
62
63 /// returns the InsetCode corresponding to the \c name.
64 /// Eg, insetCode("branch") == BRANCH_CODE
65 InsetCode insetCode(std::string const & name);
66 /// returns the Inset name corresponding to the \c InsetCode.
67 /// Eg, insetName(BRANCH_CODE) == "branch"
68 std::string insetName(InsetCode);
69 /// returns the Inset name corresponding to the \c InsetCode.
70 /// Eg, insetDisplayName(BRANCH_CODE) == _("Branch")
71 docstring insetDisplayName(InsetCode);
72
73 /// Common base class to all insets
74
75 // Do not add _any_ (non-static) data members as this would inflate
76 // everything storing large quantities of insets. Mathed e.g. would
77 // suffer.
78
79 class Inset {
80 public:
81         ///
82         enum EntryDirection {
83                 ENTRY_DIRECTION_IGNORE,
84                 ENTRY_DIRECTION_RIGHT,
85                 ENTRY_DIRECTION_LEFT,
86         };
87         ///
88         typedef ptrdiff_t  difference_type;
89         /// short of anything else reasonable
90         typedef size_t     size_type;
91         /// type for cell indices
92         typedef size_t     idx_type;
93         /// type for cursor positions
94         typedef ptrdiff_t  pos_type;
95         /// type for row numbers
96         typedef size_t     row_type;
97         /// type for column numbers
98         typedef size_t     col_type;
99
100         /// virtual base class destructor
101         virtual ~Inset() {}
102
103         /// change associated Buffer
104         virtual void setBuffer(Buffer & buffer);
105         /// remove the buffer reference
106         void resetBuffer() { setBuffer( *static_cast<Buffer *>(0)); }
107         /// retrieve associated Buffer
108         virtual Buffer & buffer();
109         virtual Buffer const & buffer() const;
110         /// Returns true if buffer_ actually points to a Buffer that has
111         /// been loaded into LyX and is still open. Note that this will
112         /// always return false for cloned Buffers. If you want to allow
113         /// for the case of cloned Buffers, use isBufferValid().
114         bool isBufferLoaded() const;
115         /// Returns true if this is a loaded buffer or a cloned buffer.
116         bool isBufferValid() const;
117
118         /// initialize view for this inset.
119         /**
120           * This is typically used after this inset is created interactively.
121           * Intented purpose is to sanitize internal state with regard to current
122           * Buffer. The default implementation calls buffer().updateBuffer() if
123           * the inset is labeled.
124           *
125           * \sa isLabeled()
126           **/
127         virtual void initView() {};
128         /// \return true if this inset is labeled.
129         virtual bool isLabeled() const { return false; }
130
131         /// identification as math inset
132         virtual InsetMath * asInsetMath() { return 0; }
133         /// identification as math inset
134         virtual InsetMath const * asInsetMath() const { return 0; }
135         /// true for 'math' math inset, but not for e.g. mbox
136         virtual bool inMathed() const { return false; }
137         /// is this inset based on the InsetText class?
138         virtual InsetText * asInsetText() { return 0; }
139         /// is this inset based on the InsetText class?
140         virtual InsetText const * asInsetText() const { return 0; }
141         /// is this inset based on the InsetCollapsable class?
142         virtual InsetCollapsable * asInsetCollapsable() { return 0; }
143         /// is this inset based on the InsetCollapsable class?
144         virtual InsetCollapsable const * asInsetCollapsable() const { return 0; }
145         /// is this inset based on the InsetTabular class?
146         virtual InsetTabular * asInsetTabular() { return 0; }
147         /// is this inset based on the InsetTabular class?
148         virtual InsetTabular const * asInsetTabular() const { return 0; }
149         /// is this inset based on the InsetCommand class?
150         virtual InsetCommand * asInsetCommand() { return 0; }
151         /// is this inset based on the InsetCommand class?
152         virtual InsetCommand const * asInsetCommand() const { return 0; }
153
154         /// the real dispatcher
155         void dispatch(Cursor & cur, FuncRequest & cmd);
156         /**
157          * \returns true if this function made a definitive decision on
158          * whether the inset wants to handle the request \p cmd or not.
159          * The result of this decision is put into \p status.
160          *
161          * Every request that is enabled in this method needs to be handled
162          * in doDispatch(). Normally we have a 1:1 relationship between the
163          * requests handled in getStatus() and doDispatch(), but there are
164          * some exceptions:
165          * - A request that is disabled in getStatus() does not need to
166          *   appear in doDispatch(). It is guaranteed that doDispatch()
167          *   is never called with this request.
168          * - A few requests are en- or disabled in Inset::getStatus().
169          *   These need to be handled in the doDispatch() methods of the
170          *   derived insets, since Inset::doDispatch() has not enough
171          *   information to handle them.
172          * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
173          *   are dispatched directly
174          */
175         virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
176                 FuncStatus & status) const;
177
178         /// cursor enters
179         virtual void edit(Cursor & cur, bool front, 
180                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
181         /// cursor enters
182         virtual Inset * editXY(Cursor & cur, int x, int y);
183
184         /// compute the size of the object returned in dim
185         virtual void metrics(MetricsInfo & mi, Dimension & dim) const = 0;
186         /// draw inset and update (xo, yo)-cache
187         virtual void draw(PainterInfo & pi, int x, int y) const = 0;
188         /// draw inset selection if necessary
189         virtual void drawSelection(PainterInfo &, int, int) const {}
190         /// draw inset background if the inset has an own background and a
191         /// selection is drawn by drawSelection.
192         virtual void drawBackground(PainterInfo &, int, int) const {}
193         ///
194         virtual bool editing(BufferView const * bv) const;
195         ///
196         virtual bool showInsetDialog(BufferView *) const;
197
198         /// draw inset decoration if necessary.
199         /// This can use \c drawMarkers() for example.
200         virtual void drawDecoration(PainterInfo &, int, int) const {}
201         /// draw four angular markers
202         void drawMarkers(PainterInfo & pi, int x, int y) const;
203         /// draw two angular markers
204         void drawMarkers2(PainterInfo & pi, int x, int y) const;
205         /// add space for markers
206         void metricsMarkers(Dimension & dim, int framesize = 1) const;
207         /// add space for markers
208         void metricsMarkers2(Dimension & dim, int framesize = 1) const;
209         /// last drawn position for 'important' insets
210         int xo(BufferView const & bv) const;
211         /// last drawn position for 'important' insets
212         int yo(BufferView const & bv) const;
213         /// set x/y drawing position cache if available
214         virtual void setPosCache(PainterInfo const &, int, int) const;
215         ///
216         void setDimCache(MetricsInfo const &, Dimension const &) const;
217         /// do we cover screen position x/y?
218         virtual bool covers(BufferView const & bv, int x, int y) const;
219         /// get the screen positions of the cursor (see note in Cursor.cpp)
220         virtual void cursorPos(BufferView const & bv,
221                 CursorSlice const & sl, bool boundary, int & x, int & y) const;
222
223         /// Allow multiple blanks
224         virtual bool isFreeSpacing() const;
225         /// Don't eliminate empty paragraphs
226         virtual bool allowEmpty() const;
227         /// Force inset into LTR environment if surroundings are RTL
228         virtual bool forceLTR() const;
229
230         /// Where should we go when we press the up or down cursor key?
231         virtual bool idxUpDown(Cursor & cur, bool up) const;
232         /// Move one cell backwards
233         virtual bool idxBackward(Cursor &) const { return false; }
234         /// Move one cell forward
235         virtual bool idxForward(Cursor &) const { return false; }
236
237         /// Move to the next cell
238         virtual bool idxNext(Cursor &) const { return false; }
239         /// Move to the previous cell
240         virtual bool idxPrev(Cursor &) const { return false; }
241
242         /// Target pos when we enter the inset while moving forward
243         virtual bool idxFirst(Cursor &) const { return false; }
244         /// Target pos when we enter the inset while moving backwards
245         virtual bool idxLast(Cursor &) const { return false; }
246
247         /// Delete a cell and move cursor
248         virtual bool idxDelete(idx_type &) { return false; }
249         /// pulls cell after pressing erase
250         virtual void idxGlue(idx_type) {}
251         /// returns list of cell indices that are "between" from and to for
252         /// selection purposes
253         virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
254
255         /// to which column belongs a cell with a given index?
256         virtual col_type col(idx_type) const { return 0; }
257         /// to which row belongs a cell with a given index?
258         virtual row_type row(idx_type) const { return 0; }
259         /// cell index corresponding to row and column;
260         virtual idx_type index(row_type row, col_type col) const;
261         /// any additional x-offset when drawing a cell?
262         virtual int cellXOffset(idx_type) const { return 0; }
263         /// any additional y-offset when drawing a cell?
264         virtual int cellYOffset(idx_type) const { return 0; }
265         /// number of embedded cells
266         virtual size_t nargs() const { return 0; }
267         /// number of rows in gridlike structures
268         virtual size_t nrows() const { return 0; }
269         /// number of columns in gridlike structures
270         virtual size_t ncols() const { return 0; }
271         /// Is called when the cursor leaves this inset.
272         /// Returns true if cursor is now invalid, e.g. if former 
273         /// insets in higher cursor slices of \c old do not exist 
274         /// anymore.
275         /// \c old is the old cursor, the last slice points to this.
276         /// \c cur is the new cursor. Use the update flags to cause a redraw.
277         virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
278                 { return false; }
279         /// Is called when the cursor enters this inset.
280         /// Returns true if cursor is now invalid, e.g. if former 
281         /// insets in higher cursor slices of \c old do not exist 
282         /// anymore.
283         /// \c cur is the new cursor, some slice points to this. Use the update flags to cause a redraw.
284         virtual bool notifyCursorEnters(Cursor & /*cur*/)
285                 { return false; }
286         /// is called when the mouse enters or leaves this inset
287         /// return true if this inset needs a repaint
288         virtual bool setMouseHover(BufferView const *, bool) { return false; }
289         /// return true if this inset is hovered (under mouse)
290         /// This is by now only used by mathed to draw corners 
291         /// (Inset::drawMarkers() and Inset::drawMarkers2()).
292         /// Other insets do not have to redefine this function to 
293         /// return the correct status of mouseHovered.
294         virtual bool mouseHovered(BufferView const *) const { return false; }
295
296         /// request "external features"
297         virtual void validate(LaTeXFeatures &) const {}
298
299         /// Validate LFUN_INSET_MODIFY argument.
300         virtual bool validateModifyArgument(docstring const &) const { return true; }
301
302         /// describe content if cursor inside
303         virtual void infoize(odocstream &) const {}
304         /// describe content if cursor behind
305         virtual void infoize2(odocstream &) const {}
306
307         enum { PLAINTEXT_NEWLINE = 10000 };
308
309         /// plain text output in ucs4 encoding
310         /// return the number of characters; in case of multiple lines of
311         /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
312         virtual int plaintext(odocstream &, OutputParams const &) const = 0;
313         /// docbook output
314         virtual int docbook(odocstream & os, OutputParams const &) const;
315         /// XHTML output
316         /// the inset is expected to write XHTML to the XHTMLStream
317         /// \return any "deferred" material that should be written outside the
318         /// normal stream, and which will in fact be written after the current
319         /// paragraph closes. this is appropriate e.g. for floats.
320         virtual docstring xhtml(XHTMLStream & xs, OutputParams const &) const;
321         /// the string that is passed to the TOC
322         virtual void tocString(odocstream &) const {}
323
324         /// can the contents of the inset be edited on screen ?
325         // true for InsetCollapsables (not ButtonOnly) (not InsetInfo), InsetText
326         virtual bool editable() const;
327         /// has the Inset settings that can be modified in a dialog ?
328         virtual bool hasSettings() const;
329         /// can we go further down on mouse click?
330         // true for InsetCaption, InsetCollapsables (not ButtonOnly), InsetTabular
331         virtual bool descendable(BufferView const &) const { return false; }
332         /// is this an inset that can be moved into?
333         /// FIXME: merge with editable()
334         // true for InsetTabular & InsetText
335         virtual bool isActive() const { return nargs() > 0; }
336
337         /// does this contain text that can be change track marked in DVI?
338         virtual bool canTrackChanges() const { return false; }
339         /// return true if the inset should be removed automatically
340         virtual bool autoDelete() const;
341
342         /// Returns true if the inset supports completions.
343         virtual bool completionSupported(Cursor const &) const { return false; }
344         /// Returns true if the inset supports inline completions at the
345         /// cursor position. In this case the completion might be stored
346         /// in the BufferView's inlineCompletion property.
347         virtual bool inlineCompletionSupported(Cursor const & /*cur*/) const 
348                 { return false; }
349         /// Return true if the inline completion should be automatic.
350         virtual bool automaticInlineCompletion() const { return true; }
351         /// Return true if the popup completion should be automatic.
352         virtual bool automaticPopupCompletion() const { return true; }
353         /// Return true if the cursor should indicate a completion.
354         virtual bool showCompletionCursor() const { return true; }
355         /// Returns completion suggestions at cursor position. Return an
356         /// null pointer if no completion is a available or possible.
357         /// The caller is responsible to free the returned object!
358         virtual CompletionList const * createCompletionList(Cursor const &) const 
359                 { return 0; }
360         /// Returns the completion prefix to filter the suggestions for completion.
361         /// This is only called if completionList returned a non-null list.
362         virtual docstring completionPrefix(Cursor const &) const;
363         /// Do a completion at the cursor position. Return true on success.
364         /// The completion does not contain the prefix. If finished is true, the
365         /// completion is final. If finished is false, completion might only be
366         /// a partial completion.
367         virtual bool insertCompletion(Cursor & /*cur*/, 
368                 docstring const & /*completion*/, bool /*finished*/) 
369                 { return false; }
370         /// Get the completion inset position and size
371         virtual void completionPosAndDim(Cursor const &, int & /*x*/, int & /*y*/, 
372                 Dimension & /*dim*/) const {}
373
374         /// returns true if the inset can hold an inset of given type
375         virtual bool insetAllowed(InsetCode) const { return false; }
376         /// should this inset use the empty layout by default rather than 
377         /// the standard layout? (default: only if that is forced.)
378         virtual bool usePlainLayout() const { return forcePlainLayout(); }
379         /// if this inset has paragraphs should they be forced to use the
380         /// empty layout?
381         virtual bool forcePlainLayout(idx_type = 0) const { return false; }
382         /// if this inset has paragraphs should the user be allowed to
383         /// customize alignment, etc?
384         virtual bool allowParagraphCustomization(idx_type = 0) const { return true; }
385         /// Is the width forced to some value?
386         virtual bool hasFixedWidth() const { return false; }
387
388         /// Is the content of this inset part of the output document?
389         virtual bool producesOutput() const { return true; }
390
391         /// \return Tool tip for this inset.
392         /// This default implementation returns an empty string.
393         virtual docstring toolTip(BufferView const & bv, int x, int y) const;
394         
395         /// \return Context menu identifier for this inset.
396         /// This default implementation returns an empty string.
397         virtual docstring contextMenu(BufferView const & bv, int x, int y) const;
398
399         // FIXME This should really disappear in favor of 
400         //      docstring name() const { return from_ascii(insetName(lyxCode()))); }
401         // There's no reason to be using different names in different places.
402         // But to do this we would need to change the file format, since the names
403         // used there don't correspond to what is used here. 
404         ///
405         virtual docstring name() const;
406         ///
407         virtual InsetLayout const & getLayout() const;
408         /// Is this inset's layout defined in the document's textclass?
409         bool undefined() const;
410         /// used to toggle insets
411         /// is the inset open?
412         /// should this inset be handled like a normal charater
413         virtual bool isChar() const { return false; }
414         /// is this equivalent to a letter?
415         virtual bool isLetter() const { return false; }
416         /// is this equivalent to a space (which is BTW different from
417         /// a line separator)?
418         virtual bool isSpace() const { return false; }
419         /// is this an expandible space (rubber length)?
420         virtual bool isStretchableSpace() const { return false; }
421
422         enum DisplayType {
423                 Inline = 0,
424                 AlignLeft,
425                 AlignCenter,
426                 AlignRight
427         };
428
429         /// should we have a non-filled line before this inset?
430         virtual DisplayType display() const { return Inline; }
431         ///
432         virtual LyXAlignment contentAlignment() const { return LYX_ALIGN_NONE; }
433         /// should we break lines after this inset?
434         virtual bool isLineSeparator() const { return false; }
435         /// should paragraph indendation be ommitted in any case?
436         virtual bool neverIndent() const { return false; }
437         /// dumps content to lyxerr
438         virtual void dump() const;
439         /// write inset in .lyx format
440         virtual void write(std::ostream &) const {}
441         /// read inset in .lyx format
442         virtual void read(Lexer &) {}
443         /** Export the inset to LaTeX.
444          *  Don't use a temporary stringstream if the final output is
445          *  supposed to go to a file.
446          *  \sa Buffer::writeLaTeXSource for the reason.
447          *  \return the number of rows (\n's) of generated LaTeX code.
448          */
449         virtual int latex(odocstream &, OutputParams const &) const { return 0; }
450         /// returns true to override begin and end inset in file
451         virtual bool directWrite() const;
452         ///
453         virtual bool allowSpellCheck() const { return false; }
454
455         /// if this insets owns text cells (e.g. InsetText) return cell num
456         virtual Text * getText(int /*num*/) const { return 0; }
457
458         /** Adds a LaTeX snippet to the Preview Loader for transformation
459          *  into a bitmap image. Does not start the laoding process.
460          *
461          *  Most insets have no interest in this capability, so the method
462          *  defaults to empty.
463          */
464         virtual void addPreview(DocIterator const &,
465                 graphics::PreviewLoader &) const {}
466
467         /** Classifies the unicode characters appearing in a math inset
468          *  depending on whether they are to be translated as latex
469          *  math/text commands or used as math symbols without translation.
470          *
471          *  Only math insets have interest in this classification, so the
472          *  method defaults to empty.
473          */
474         virtual void initUnicodeMath() const {}
475
476         /// Add an entry to the TocList
477         /// pit is the ParConstIterator of the paragraph containing the inset
478         virtual void addToToc(DocIterator const &) {}
479         /// Fill keys with BibTeX information
480         virtual void fillWithBibKeys(BiblioInfo &, InsetIterator const &) const {}
481         /// Update the counters of this inset and of its contents.
482         /// The boolean indicates whether we are preparing for output, e.g.,
483         /// of XHTML.
484         virtual void updateBuffer(ParIterator const &, UpdateType) {}
485
486         /// Updates the inset's dialog
487         virtual Buffer const * updateFrontend() const;
488
489 public:
490         /// returns LyX code associated with the inset. Used for TOC, ...)
491         virtual InsetCode lyxCode() const { return NO_CODE; }
492
493         /// -1: text mode, 1: math mode, 0 undecided
494         enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
495         /// return text or mathmode if that is possible to determine
496         virtual mode_type currentMode() const { return UNDECIDED_MODE; }
497         /// returns whether changing mode during latex export is forbidden
498         virtual bool lockedMode() const { return false; }
499         /// returns whether only ascii chars are allowed during latex export
500         virtual bool asciiOnly() const { return false; }
501         /// returns whether this inset is allowed in other insets of given mode
502         virtual bool allowedIn(mode_type) const { return true; }
503         /**
504          * Is this inset allowed within a font change?
505          *
506          * FIXME: noFontChange means currently that the font change is closed
507          * in LaTeX before the inset, and that the contents of the inset
508          * will be in default font. This should be changed so that the inset
509          * changes the font again.
510          */
511         virtual bool noFontChange() const { return false; }
512
513         /// set the change for the entire inset
514         virtual void setChange(Change const &) {}
515         /// accept the changes within the inset
516         virtual void acceptChanges() {}
517         /// reject the changes within the inset
518         virtual void rejectChanges() {}
519
520         ///
521         virtual Dimension const dimension(BufferView const &) const;
522         ///
523         int scroll() const { return 0; }
524         ///
525         virtual ColorCode backgroundColor(PainterInfo const &) const;
526         ///
527         virtual ColorCode labelColor() const;
528         //
529         enum { TEXT_TO_INSET_OFFSET = 4 };
530
531 protected:
532         /// Constructors
533         Inset(Buffer * buf) : buffer_(buf) {}
534         Inset(Inset const &) : buffer_(0) {}
535
536         /// replicate ourselves
537         friend class InsetList;
538         friend class MathAtom;
539         virtual Inset * clone() const = 0;
540
541         /** The real dispatcher.
542          *  Gets normally called from Cursor::dispatch(). Cursor::dispatch()
543          *  assumes the common case of 'LFUN handled, need update'.
544          *  This has to be overriden by calling Cursor::undispatched() or
545          *  Cursor::noScreenUpdate() if appropriate.
546          *  If you need to call the dispatch method of some inset directly
547          *  you may have to explicitly request an update at that place. Don't
548          *  do it in doDispatch(), since that causes nested updates when
549          *  called from Cursor::dispatch(), and these can lead to crashes.
550          *  \sa getStatus
551          */
552         virtual void doDispatch(Cursor & cur, FuncRequest & cmd);
553
554         Buffer * buffer_;
555 };
556
557 } // namespace lyx
558
559 #endif