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