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