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