]> git.lyx.org Git - lyx.git/blob - src/insets/Inset.h
Add const versions of Inset::asInsetMath.
[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 BufferView;
31 class Change;
32 class CompletionList;
33 class Cursor;
34 class CursorSlice;
35 class Dimension;
36 class DocIterator;
37 class FuncRequest;
38 class FuncStatus;
39 class InsetCollapsable;
40 class InsetIterator;
41 class InsetLayout;
42 class InsetList;
43 class InsetMath;
44 class InsetTabular;
45 class InsetText;
46 class LaTeXFeatures;
47 class Lexer;
48 class MathAtom;
49 class MetricsInfo;
50 class OutputParams;
51 class PainterInfo;
52 class ParConstIterator;
53 class ParIterator;
54 class Text;
55 class TocList;
56
57 namespace graphics { class PreviewLoader; }
58
59
60 /** returns the InsetCode corresponding to the \c name.
61 *   Eg, insetCode("branch") == BRANCH_CODE
62 *   Implemented in 'Inset.cpp'.
63 */
64 InsetCode insetCode(std::string const & name);
65 /// the other way
66 std::string insetName(InsetCode);
67
68 /// Common base class to all insets
69
70 // Do not add _any_ (non-static) data members as this would inflate
71 // everything storing large quantities of insets. Mathed e.g. would
72 // suffer.
73
74 class Inset {
75 public:
76         ///
77         enum EntryDirection {
78                 ENTRY_DIRECTION_IGNORE,
79                 ENTRY_DIRECTION_RIGHT,
80                 ENTRY_DIRECTION_LEFT,
81         };
82         ///
83         typedef ptrdiff_t  difference_type;
84         /// short of anything else reasonable
85         typedef size_t     size_type;
86         /// type for cell indices
87         typedef size_t     idx_type;
88         /// type for cursor positions
89         typedef ptrdiff_t  pos_type;
90         /// type for row numbers
91         typedef size_t     row_type;
92         /// type for column numbers
93         typedef size_t     col_type;
94
95         /// virtual base class destructor
96         virtual ~Inset() {}
97
98         /// change associated Buffer
99         virtual void setBuffer(Buffer & buffer);
100         /// remove the buffer reference
101         void resetBuffer() { setBuffer( *static_cast<Buffer *>(0)); }
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         /// identification as math inset
125         virtual InsetMath const * asInsetMath() const { return 0; }
126         /// true for 'math' math inset, but not for e.g. mbox
127         virtual bool inMathed() const { return false; }
128         /// is this inset based on the InsetText class?
129         virtual InsetText * asInsetText() { return 0; }
130         /// is this inset based on the InsetText class?
131         virtual InsetText const * asInsetText() const { return 0; }
132         /// is this inset based on the InsetCollapsable class?
133         virtual InsetCollapsable * asInsetCollapsable() { return 0; }
134         /// is this inset based on the InsetCollapsable class?
135         virtual InsetCollapsable const * asInsetCollapsable() const { return 0; }
136         /// is this inset based on the InsetTabular class?
137         virtual InsetTabular * asInsetTabular() { return 0; }
138         /// is this inset based on the InsetTabular class?
139         virtual InsetTabular const * asInsetTabular() const { return 0; }
140
141         /// the real dispatcher
142         void dispatch(Cursor & cur, FuncRequest & cmd);
143         /**
144          * \returns true if this function made a definitive decision on
145          * whether the inset wants to handle the request \p cmd or not.
146          * The result of this decision is put into \p status.
147          *
148          * Every request that is enabled in this method needs to be handled
149          * in doDispatch(). Normally we have a 1:1 relationship between the
150          * requests handled in getStatus() and doDispatch(), but there are
151          * some exceptions:
152          * - A request that is disabled in getStatus() does not need to
153          *   appear in doDispatch(). It is guaranteed that doDispatch()
154          *   is never called with this request.
155          * - A few requests are en- or disabled in Inset::getStatus().
156          *   These need to be handled in the doDispatch() methods of the
157          *   derived insets, since Inset::doDispatch() has not enough
158          *   information to handle them.
159          * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
160          *   are dispatched directly
161          */
162         virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
163                 FuncStatus & status) const;
164
165         /// cursor enters
166         virtual void edit(Cursor & cur, bool front, 
167                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
168         /// cursor enters
169         virtual Inset * editXY(Cursor & cur, int x, int y);
170
171         /// compute the size of the object returned in dim
172         /// \retval true if metrics changed.
173         virtual void metrics(MetricsInfo & mi, Dimension & dim) const = 0;
174         /// draw inset and update (xo, yo)-cache
175         virtual void draw(PainterInfo & pi, int x, int y) const = 0;
176         /// draw inset selection if necessary
177         virtual void drawSelection(PainterInfo &, int, int) const {}
178         /// draw inset background if the inset has an own background and a
179         /// selection is drawn by drawSelection.
180         virtual void drawBackground(PainterInfo &, int, int) const {}
181         ///
182         virtual bool editing(BufferView const * bv) const;
183         ///
184         virtual bool showInsetDialog(BufferView *) const { return false; }
185
186         /// draw inset decoration if necessary.
187         /// This can use \c drawMarkers() for example.
188         virtual void drawDecoration(PainterInfo &, int, int) const {}
189         /// draw four angular markers
190         void drawMarkers(PainterInfo & pi, int x, int y) const;
191         /// draw two angular markers
192         void drawMarkers2(PainterInfo & pi, int x, int y) const;
193         /// add space for markers
194         void metricsMarkers(Dimension & dim, int framesize = 1) const;
195         /// add space for markers
196         void metricsMarkers2(Dimension & dim, int framesize = 1) const;
197         /// last drawn position for 'important' insets
198         int xo(BufferView const & bv) const;
199         /// last drawn position for 'important' insets
200         int yo(BufferView const & bv) const;
201         /// set x/y drawing position cache if available
202         virtual void setPosCache(PainterInfo const &, int, int) const;
203         ///
204         void setDimCache(MetricsInfo const &, Dimension const &) const;
205         /// do we cover screen position x/y?
206         virtual bool covers(BufferView const & bv, int x, int y) const;
207         /// get the screen positions of the cursor (see note in Cursor.cpp)
208         virtual void cursorPos(BufferView const & bv,
209                 CursorSlice const & sl, bool boundary, int & x, int & y) const;
210
211         /// Allow multiple blanks
212         virtual bool isFreeSpacing() const;
213         /// Don't eliminate empty paragraphs
214         virtual bool allowEmpty() const;
215         /// Force inset into LTR environment if surroundings are RTL?
216         virtual bool forceLTR() const;
217
218         /// Where should we go when we press the up or down cursor key?
219         virtual bool idxUpDown(Cursor & cur, bool up) const;
220         /// Move one cell backwards
221         virtual bool idxBackward(Cursor &) const { return false; }
222         /// Move one cell forward
223         virtual bool idxForward(Cursor &) const { return false; }
224
225         /// Move to the next cell
226         virtual bool idxNext(Cursor &) const { return false; }
227         /// Move to the previous cell
228         virtual bool idxPrev(Cursor &) const { return false; }
229
230         /// Target pos when we enter the inset while moving forward
231         virtual bool idxFirst(Cursor &) const { return false; }
232         /// Target pos when we enter the inset while moving backwards
233         virtual bool idxLast(Cursor &) const { return false; }
234
235         /// Delete a cell and move cursor
236         virtual bool idxDelete(idx_type &) { return false; }
237         /// pulls cell after pressing erase
238         virtual void idxGlue(idx_type) {}
239         /// returns list of cell indices that are "between" from and to for
240         /// selection purposes
241         virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
242
243         /// to which column belongs a cell with a given index?
244         virtual col_type col(idx_type) const { return 0; }
245         /// to which row belongs a cell with a given index?
246         virtual row_type row(idx_type) const { return 0; }
247         /// cell index corresponding to row and column;
248         virtual idx_type index(row_type row, col_type col) const;
249         /// any additional x-offset when drawing a cell?
250         virtual int cellXOffset(idx_type) const { return 0; }
251         /// any additional y-offset when drawing a cell?
252         virtual int cellYOffset(idx_type) const { return 0; }
253         /// number of embedded cells
254         virtual size_t nargs() const { return 0; }
255         /// number of rows in gridlike structures
256         virtual size_t nrows() const { return 0; }
257         /// number of columns in gridlike structures
258         virtual size_t ncols() const { return 0; }
259         /// Is called when the cursor leaves this inset.
260         /// Returns true if cursor is now invalid, e.g. if former 
261         /// insets in higher cursor slices of \c old do not exist 
262         /// anymore.
263         /// \c old is the old cursor, the last slice points to this.
264         /// \c cur is the new cursor. Use the update flags to cause a redraw.
265         virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
266                 { return false; }
267         /// Is called when the cursor enters this inset.
268         /// Returns true if cursor is now invalid, e.g. if former 
269         /// insets in higher cursor slices of \c old do not exist 
270         /// anymore.
271         /// \c cur is the new cursor, some slice points to this. Use the update flags to cause a redraw.
272         virtual bool notifyCursorEnters(Cursor & /*cur*/)
273                 { return false; }
274         /// is called when the mouse enter or leave this inset
275         /// return true if this inset needs repaint
276         virtual bool setMouseHover(bool) { return false; }
277         /// return true if this inset is hovered (under mouse)
278         /// This is by now only used by mathed to draw corners 
279         /// (Inset::drawMarkers() and Inset::drawMarkers2()).
280         /// Other insets do not have to redefine this function to 
281         /// return the correct status of mouseHovered.
282         virtual bool mouseHovered() const { return false; }
283
284         /// request "external features"
285         virtual void validate(LaTeXFeatures &) const {}
286
287         /// describe content if cursor inside
288         virtual void infoize(odocstream &) const {}
289         /// describe content if cursor behind
290         virtual void infoize2(odocstream &) const {}
291
292         enum { PLAINTEXT_NEWLINE = 10000 };
293
294         /// plain text output in ucs4 encoding
295         /// return the number of characters; in case of multiple lines of
296         /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
297         virtual int plaintext(odocstream &, OutputParams const &) const = 0;
298         /// docbook output
299         virtual int docbook(odocstream & os, OutputParams const &) const;
300         /// LyX HTML output
301         virtual docstring xhtml(odocstream & os, OutputParams const &) const;
302         /// the string that is passed to the TOC
303         virtual void tocString(odocstream &) const {}
304
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() const;
389         /// Is this inset's layout defined in the document's textclass?
390         bool undefined() const;
391         /// used to toggle insets
392         /// is the inset open?
393         /// should this inset be handled like a normal charater
394         virtual bool isChar() const { return false; }
395         /// is this equivalent to a letter?
396         virtual bool isLetter() const { return false; }
397         /// is this equivalent to a space (which is BTW different from
398         /// a line separator)?
399         virtual bool isSpace() const { return false; }
400         /// is this an expandible space (rubber length)?
401         virtual bool isStretchableSpace() const { return false; }
402
403         enum DisplayType {
404                 Inline = 0,
405                 AlignLeft,
406                 AlignCenter,
407                 AlignRight
408         };
409
410         /// should we have a non-filled line before this inset?
411         virtual DisplayType display() const { return Inline; }
412         ///
413         virtual LyXAlignment contentAlignment() const { return LYX_ALIGN_NONE; }
414         /// should we break lines after this inset?
415         virtual bool isLineSeparator() const { return false; }
416         /// should paragraph indendation be ommitted in any case?
417         virtual bool neverIndent() const { return false; }
418         /// dumps content to lyxerr
419         virtual void dump() const;
420         /// write inset in .lyx format
421         virtual void write(std::ostream &) const {}
422         /// read inset in .lyx format
423         virtual void read(Lexer &) {}
424         /** Export the inset to LaTeX.
425          *  Don't use a temporary stringstream if the final output is
426          *  supposed to go to a file.
427          *  \sa Buffer::writeLaTeXSource for the reason.
428          *  \return the number of rows (\n's) of generated LaTeX code.
429          */
430         virtual int latex(odocstream &, OutputParams const &) const { return 0; }
431         /// returns true to override begin and end inset in file
432         virtual bool directWrite() const;
433         ///
434         virtual bool allowSpellCheck() const { return false; }
435
436         /// if this insets owns text cells (e.g. InsetText) return cell num
437         virtual Text * getText(int /*num*/) const { return 0; }
438
439         /** Adds a LaTeX snippet to the Preview Loader for transformation
440          *  into a bitmap image. Does not start the laoding process.
441          *
442          *  Most insets have no interest in this capability, so the method
443          *  defaults to empty.
444          */
445         virtual void addPreview(graphics::PreviewLoader &) const {}
446
447         /** Classifies the unicode characters appearing in a math inset
448          *  depending on whether they are to be translated as latex
449          *  math/text commands or used as math symbols without translation.
450          *
451          *  Only math insets have interest in this classification, so the
452          *  method defaults to empty.
453          */
454         virtual void initUnicodeMath() const {}
455
456         /// Add an entry to the TocList
457         /// pit is the ParConstIterator of the paragraph containing the inset
458         virtual void addToToc(DocIterator const &) {}
459         /// Fill keys with BibTeX information
460         virtual void fillWithBibKeys(BiblioInfo &, InsetIterator const &) const {}
461         /// Update the counters of this inset and of its contents
462         virtual void updateLabels(ParIterator const &) {}
463
464         /// Updates the inset's dialog
465         virtual Buffer const * updateFrontend() const;
466
467 public:
468         /// returns LyX code associated with the inset. Used for TOC, ...)
469         virtual InsetCode lyxCode() const { return NO_CODE; }
470
471         /// -1: text mode, 1: math mode, 0 undecided
472         enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
473         /// return text or mathmode if that is possible to determine
474         virtual mode_type currentMode() const { return UNDECIDED_MODE; }
475         /// returns whether changing mode during latex export is forbidden
476         virtual bool lockedMode() const { return false; }
477         /// returns whether this inset is allowed in other insets of given mode
478         virtual bool allowedIn(mode_type) const { return true; }
479         /**
480          * Is this inset allowed within a font change?
481          *
482          * FIXME: noFontChange means currently that the font change is closed
483          * in LaTeX before the inset, and that the contents of the inset
484          * will be in default font. This should be changed so that the inset
485          * changes the font again.
486          */
487         virtual bool noFontChange() const { return false; }
488
489         /// set the change for the entire inset
490         virtual void setChange(Change const &) {}
491         /// accept the changes within the inset
492         virtual void acceptChanges() {};
493         /// reject the changes within the inset
494         virtual void rejectChanges() {};
495
496         ///
497         virtual Dimension const dimension(BufferView const &) const;
498         ///
499         int scroll() const { return 0; }
500         ///
501         virtual ColorCode backgroundColor() const;
502         ///
503         virtual ColorCode labelColor() const;
504         ///
505         enum CollapseStatus {
506                 Collapsed,
507                 Open
508         };
509         ///
510         virtual void setStatus(Cursor &, CollapseStatus) {}
511         //
512         enum { TEXT_TO_INSET_OFFSET = 4 };
513
514 protected:
515         /// Constructors
516         Inset() : buffer_(0) {}
517         Inset(Inset const &) : buffer_(0) {}
518
519         /// replicate ourselves
520         friend class InsetList;
521         friend class MathAtom;
522         virtual Inset * clone() const = 0;
523
524         /** The real dispatcher.
525          *  Gets normally called from Cursor::dispatch(). Cursor::dispatch()
526          *  assumes the common case of 'LFUN handled, need update'.
527          *  This has to be overriden by calling Cursor::undispatched() or
528          *  Cursor::noUpdate() if appropriate.
529          *  If you need to call the dispatch method of some inset directly
530          *  you may have to explicitly request an update at that place. Don't
531          *  do it in doDispatch(), since that causes nested updates when
532          *  called from Cursor::dispatch(), and these can lead to crashes.
533          *  \sa getStatus
534          */
535         virtual void doDispatch(Cursor & cur, FuncRequest & cmd);
536
537         Buffer * buffer_;
538 };
539
540 } // namespace lyx
541
542 #endif