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