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