]> git.lyx.org Git - lyx.git/blob - src/insets/Inset.h
visual mode for bidi cursor movement --- in tables
[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
21 #include "support/strfwd.h"
22 #include "support/types.h"
23
24
25 namespace lyx {
26
27 class BiblioInfo;
28 class Buffer;
29 class BufferParams;
30 class BufferView;
31 class Change;
32 class CompletionList;
33 class Cursor;
34 class CursorSlice;
35 class Dimension;
36 class DocIterator;
37 class FuncRequest;
38 class FuncStatus;
39 class InsetCollapsable;
40 class InsetIterator;
41 class InsetLayout;
42 class InsetList;
43 class InsetMath;
44 class InsetTabular;
45 class InsetText;
46 class LaTeXFeatures;
47 class Lexer;
48 class MathAtom;
49 class MetricsInfo;
50 class OutputParams;
51 class PainterInfo;
52 class ParConstIterator;
53 class ParIterator;
54 class Text;
55 class TocList;
56 class EmbeddedFile;
57 class EmbeddedFileList;
58
59
60 namespace graphics { class PreviewLoader; }
61
62
63 /** returns the InsetCode corresponding to the \c name.
64 *   Eg, insetCode("branch") == BRANCH_CODE
65 *   Implemented in 'Inset.cpp'.
66 */
67 InsetCode insetCode(std::string const & name);
68 /// the other way
69 std::string insetName(InsetCode);
70
71 /// Common base class to all insets
72
73 // Do not add _any_ (non-static) data members as this would inflate
74 // everything storing large quantities of insets. Mathed e.g. would
75 // suffer.
76
77 class Inset {
78 public:
79         ///
80         enum EntryDirection {
81                 ENTRY_DIRECTION_IGNORE,
82                 ENTRY_DIRECTION_RIGHT,
83                 ENTRY_DIRECTION_LEFT,
84         };
85         ///
86         typedef ptrdiff_t  difference_type;
87         /// short of anything else reasonable
88         typedef size_t     size_type;
89         /// type for cell indices
90         typedef size_t     idx_type;
91         /// type for cursor positions
92         typedef ptrdiff_t  pos_type;
93         /// type for row numbers
94         typedef size_t     row_type;
95         /// type for column numbers
96         typedef size_t     col_type;
97
98         /// virtual base class destructor
99         virtual ~Inset() {}
100
101         /// change associated Buffer
102         /// FIXME this should go.
103         virtual void setBuffer(Buffer & buffer);
104         /// retrieve associated Buffer
105         virtual Buffer & buffer();
106         virtual Buffer const & buffer() const;
107
108         /// initialize view for this inset.
109         /**
110           * This is typically used after this inset is created interactively.
111           * Intented purpose is to sanitize internal state with regard to current
112           * Buffer. The default implementation calls updateLabels(buffer()) is
113           * the inset is labeled.
114           *
115           * \sa isLabeled()
116           **/
117         virtual void initView();
118         /// \return true if this inset is labeled.
119         virtual bool isLabeled() const { return false; }
120
121         /// identification as math inset
122         virtual InsetMath * asInsetMath() { return 0; }
123         /// true for 'math' math inset, but not for e.g. mbox
124         virtual bool inMathed() const { return false; }
125         /// is this inset based on the InsetText class?
126         virtual InsetText * asInsetText() { return 0; }
127         /// is this inset based on the InsetText class?
128         virtual InsetText const * asInsetText() const { return 0; }
129         /// is this inset based on the InsetCollapsable class?
130         virtual InsetCollapsable * asInsetCollapsable() { return 0; }
131         /// is this inset based on the InsetCollapsable class?
132         virtual InsetCollapsable const * asInsetCollapsable() const { return 0; }
133         /// is this inset based on the InsetTabular class?
134         virtual InsetTabular * asInsetTabular() { return 0; }
135         /// is this inset based on the InsetTabular class?
136         virtual InsetTabular const * asInsetTabular() const { return 0; }
137
138         /// the real dispatcher
139         void dispatch(Cursor & cur, FuncRequest & cmd);
140         /**
141          * \returns true if this function made a definitive decision on
142          * whether the inset wants to handle the request \p cmd or not.
143          * The result of this decision is put into \p status.
144          *
145          * Every request that is enabled in this method needs to be handled
146          * in doDispatch(). Normally we have a 1:1 relationship between the
147          * requests handled in getStatus() and doDispatch(), but there are
148          * some exceptions:
149          * - A request that is disabled in getStatus() does not need to
150          *   appear in doDispatch(). It is guaranteed that doDispatch()
151          *   is never called with this request.
152          * - A few requests are en- or disabled in Inset::getStatus().
153          *   These need to be handled in the doDispatch() methods of the
154          *   derived insets, since Inset::doDispatch() has not enough
155          *   information to handle them.
156          * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
157          *   are dispatched directly
158          */
159         virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
160                 FuncStatus & status) const;
161
162         /// cursor enters
163         virtual void edit(Cursor & cur, bool front, 
164                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
165         /// cursor enters
166         virtual Inset * editXY(Cursor & cur, int x, int y);
167
168         /// compute the size of the object returned in dim
169         /// \retval true if metrics changed.
170         virtual void metrics(MetricsInfo & mi, Dimension & dim) const = 0;
171         /// draw inset and update (xo, yo)-cache
172         virtual void draw(PainterInfo & pi, int x, int y) const = 0;
173         /// draw inset selection if necessary
174         virtual void drawSelection(PainterInfo &, int, int) const {}
175         ///
176         virtual bool editing(BufferView const * bv) const;
177         ///
178         virtual bool showInsetDialog(BufferView *) const { return false; }
179
180         /// draw inset decoration if necessary.
181         /// This can use \c drawMarkers() for example.
182         virtual void drawDecoration(PainterInfo &, int, int) const {}
183         /// draw four angular markers
184         void drawMarkers(PainterInfo & pi, int x, int y) const;
185         /// draw two angular markers
186         void drawMarkers2(PainterInfo & pi, int x, int y) const;
187         /// add space for markers
188         void metricsMarkers(Dimension & dim, int framesize = 1) const;
189         /// add space for markers
190         void metricsMarkers2(Dimension & dim, int framesize = 1) const;
191         /// last drawn position for 'important' insets
192         int xo(BufferView const & bv) const;
193         /// last drawn position for 'important' insets
194         int yo(BufferView const & bv) const;
195         /// set x/y drawing position cache if available
196         virtual void setPosCache(PainterInfo const &, int, int) const;
197         ///
198         void setDimCache(MetricsInfo const &, Dimension const &) const;
199         /// do we cover screen position x/y?
200         virtual bool covers(BufferView const & bv, int x, int y) const;
201         /// get the screen positions of the cursor (see note in Cursor.cpp)
202         virtual void cursorPos(BufferView const & bv,
203                 CursorSlice const & sl, bool boundary, int & x, int & y) const;
204
205         ///
206         virtual bool isFreeSpacing() const { return false; }
207         ///
208         virtual bool allowEmpty() const { return false; }
209         /// Force inset into LTR environment if surroundings are RTL?
210         virtual bool forceLTR() const { return false; }
211
212         /// is this an inset that can be moved into?
213         /// FIXME: merge with editable()
214         virtual bool isActive() const { return nargs() > 0; }
215         /// Where should we go when we press the up or down cursor key?
216         virtual bool idxUpDown(Cursor & cur, bool up) const;
217         /// Move one cell backwards
218         virtual bool idxBackward(Cursor &) const { return false; }
219         /// Move one cell forward
220         virtual bool idxForward(Cursor &) const { return false; }
221
222         /// Move to the next cell
223         virtual bool idxNext(Cursor &) const { return false; }
224         /// Move to the previous cell
225         virtual bool idxPrev(Cursor &) const { return false; }
226
227         /// Target pos when we enter the inset while moving forward
228         virtual bool idxFirst(Cursor &) const { return false; }
229         /// Target pos when we enter the inset while moving backwards
230         virtual bool idxLast(Cursor &) const { return false; }
231
232         /// Delete a cell and move cursor
233         virtual bool idxDelete(idx_type &) { return false; }
234         /// pulls cell after pressing erase
235         virtual void idxGlue(idx_type) {}
236         /// returns list of cell indices that are "between" from and to for
237         /// selection purposes
238         virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
239
240         /// to which column belongs a cell with a given index?
241         virtual col_type col(idx_type) const { return 0; }
242         /// to which row belongs a cell with a given index?
243         virtual row_type row(idx_type) const { return 0; }
244         /// cell index corresponding to row and column;
245         virtual idx_type index(row_type row, col_type col) const;
246         /// any additional x-offset when drawing a cell?
247         virtual int cellXOffset(idx_type) const { return 0; }
248         /// any additional y-offset when drawing a cell?
249         virtual int cellYOffset(idx_type) const { return 0; }
250         /// number of embedded cells
251         virtual size_t nargs() const { return 0; }
252         /// number of rows in gridlike structures
253         virtual size_t nrows() const { return 0; }
254         /// number of columns in gridlike structures
255         virtual size_t ncols() const { return 0; }
256         /// Is called when the cursor leaves this inset.
257         /// Returns true if cursor is now invalid, e.g. if former 
258         /// insets in higher cursor slices of \c old do not exist 
259         /// anymore.
260         /// \c old is the old cursor, i.e. there is a slice pointing to this.
261         /// \c cur is the new cursor. Use the update flags to cause a redraw.
262         virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
263                 { return false; }
264         /// is called when the mouse enter or leave this inset
265         /// return true if this inset needs repaint
266         virtual bool setMouseHover(bool) { return false; }
267         /// return true if this inset is hovered (under mouse)
268         /// This is by now only used by mathed to draw corners 
269         /// (Inset::drawMarkers() and Inset::drawMarkers2()).
270         /// Other insets do not have to redefine this function to 
271         /// return the correct status of mouseHovered.
272         virtual bool mouseHovered() const { return false; }
273
274         /// request "external features"
275         virtual void validate(LaTeXFeatures &) const {}
276
277         /// describe content if cursor inside
278         virtual void infoize(odocstream &) const {}
279         /// describe content if cursor behind
280         virtual void infoize2(odocstream &) const {}
281
282         enum { PLAINTEXT_NEWLINE = 10000 };
283
284         /// plain text output in ucs4 encoding
285         /// return the number of characters; in case of multiple lines of
286         /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
287         virtual int plaintext(odocstream &, OutputParams const &) const = 0;
288         /// docbook output
289         virtual int docbook(odocstream & os, OutputParams const &) const;
290         /// the string that is passed to the TOC
291         virtual void textString(odocstream &) const {}
292
293         /** This enum indicates by which means the inset can be modified:
294         - NOT_EDITABLE: the inset's content cannot be modified at all
295           (e.g. printindex, insetspecialchar)
296         - IS_EDITABLE: content can be edited via dialog (e.g. bibtex, index, href)
297         - HIGHLY_EDITABLE: content can be edited on screen (normally means that
298           insettext is contained, e.g. collapsables, tabular) */
299         // FIXME: This has not yet been fully implemented to math insets
300         enum EDITABLE {
301                 ///
302                 NOT_EDITABLE = 0,
303                 ///
304                 IS_EDITABLE,
305                 ///
306                 HIGHLY_EDITABLE
307         };
308         /// what appears in the minibuffer when opening
309         virtual docstring editMessage() const;
310         ///
311         virtual EDITABLE editable() const;
312         /// can we go further down on mouse click?
313         virtual bool descendable() const { return false; }
314         /// does this contain text that can be change track marked in DVI?
315         virtual bool canTrackChanges() const { return false; }
316         /// return true if the inset should be removed automatically
317         virtual bool autoDelete() const;
318
319         /// Returns true if the inset supports completions.
320         virtual bool completionSupported(Cursor const &) const { return false; }
321         /// Returns true if the inset supports inline completions at the
322         /// cursor position. In this case the completion might be stored
323         /// in the BufferView's inlineCompletion property.
324         virtual bool inlineCompletionSupported(Cursor const & /*cur*/) const 
325                 { return false; }
326         /// Return true if the inline completion should be automatic.
327         virtual bool automaticInlineCompletion() const { return true; }
328         /// Return true if the popup completion should be automatic.
329         virtual bool automaticPopupCompletion() const { return true; }
330         /// Return true if the cursor should indicate a completion.
331         virtual bool showCompletionCursor() const { return true; }
332         /// Returns completion suggestions at cursor position. Return an
333         /// null pointer if no completion is a available or possible.
334         /// The caller is responsible to free the returned object!
335         virtual CompletionList const * createCompletionList(Cursor const &) const 
336                 { return 0; }
337         /// Returns the completion prefix to filter the suggestions for completion.
338         /// This is only called if completionList returned a non-null list.
339         virtual docstring completionPrefix(Cursor const &) const;
340         /// Do a completion at the cursor position. Return true on success.
341         /// The completion does not contain the prefix. If finished is true, the
342         /// completion is final. If finished is false, completion might only be
343         /// a partial completion.
344         virtual bool insertCompletion(Cursor & /*cur*/, 
345                 docstring const & /*completion*/, bool /*finished*/) 
346                 { return false; }
347         /// Get the completion inset position and size
348         virtual void completionPosAndDim(Cursor const &, int & /*x*/, int & /*y*/, 
349                 Dimension & /*dim*/) const {}
350
351         /// returns true if the inset can hold an inset of given type
352         virtual bool insetAllowed(InsetCode) const { return false; }
353         /// should this inset use the empty layout by default rather than 
354         /// the standard layout? (default: only if that is forced.)
355         virtual bool useEmptyLayout() const { return forceEmptyLayout(); }
356         /// if this inset has paragraphs should they be forced to use the
357         /// empty layout?
358         virtual bool forceEmptyLayout(idx_type = 0) const { return false; }
359         /// if this inset has paragraphs should the user be allowed to
360         /// customize alignment, etc?
361         virtual bool allowParagraphCustomization(idx_type = 0) const { return true; }
362         /// Is the width forced to some value?
363         virtual bool hasFixedWidth() const { return false; }
364
365         /// \return Tool tip for this inset.
366         /// This default implementation returns an empty string.
367         virtual docstring toolTip(BufferView const & bv, int x, int y) const;
368         
369         /// \return Context menu identifier for this inset.
370         /// This default implementation returns an empty string.
371         virtual docstring contextMenu(BufferView const & bv, int x, int y) const;
372
373         // FIXME This should really disappear in favor of 
374         //      docstring name() const { return from_ascii(insetName(lyxCode()))); }
375         // There's no reason to be using different names in different places.
376         // But to do this we would need to change the file format, since the names
377         // used there don't correspond to what is used here. 
378         ///
379         virtual docstring name() const;
380         ///
381         virtual InsetLayout const & getLayout(BufferParams const & bp) const;
382         /// used to toggle insets
383         /// is the inset open?
384         /// should this inset be handled like a normal charater
385         virtual bool isChar() const { return false; }
386         /// is this equivalent to a letter?
387         virtual bool isLetter() const { return false; }
388         /// is this equivalent to a space (which is BTW different from
389         /// a line separator)?
390         virtual bool isSpace() const { return false; }
391         /// is this an expandible space (rubber length)?
392         virtual bool isStretchableSpace() const { return false; }
393
394         enum DisplayType {
395                 Inline = 0,
396                 AlignLeft,
397                 AlignCenter,
398                 AlignRight
399         };
400
401         /// should we have a non-filled line before this inset?
402         virtual DisplayType display() const { return Inline; }
403         /// should we break lines after this inset?
404         virtual bool isLineSeparator() const { return false; }
405         /// should paragraph indendation be ommitted in any case?
406         virtual bool neverIndent() const { return false; }
407         /// dumps content to lyxerr
408         virtual void dump() const;
409         /// write inset in .lyx format
410         virtual void write(std::ostream &) const {}
411         /// read inset in .lyx format
412         virtual void read(Lexer &) {}
413         /** Export the inset to LaTeX.
414          *  Don't use a temporary stringstream if the final output is
415          *  supposed to go to a file.
416          *  \sa Buffer::writeLaTeXSource for the reason.
417          *  \return the number of rows (\n's) of generated LaTeX code.
418          */
419         virtual int latex(odocstream &, OutputParams const &) const { return 0; }
420         /// returns true to override begin and end inset in file
421         virtual bool directWrite() const;
422         ///
423         virtual bool allowSpellCheck() const { return false; }
424
425         /// if this insets owns text cells (e.g. InsetText) return cell num
426         virtual Text * getText(int /*num*/) const { return 0; }
427
428         /** Adds a LaTeX snippet to the Preview Loader for transformation
429          *  into a bitmap image. Does not start the laoding process.
430          *
431          *  Most insets have no interest in this capability, so the method
432          *  defaults to empty.
433          */
434         virtual void addPreview(graphics::PreviewLoader &) const {}
435         /// Add an entry to the TocList
436         /// pit is the ParConstIterator of the paragraph containing the inset
437         virtual void addToToc(ParConstIterator const &) const {}
438         /// report files that can be embedded with the lyx file
439         virtual void registerEmbeddedFiles(EmbeddedFileList &) const {}
440         /// update the properties of an embedded file of an inset
441         /// the name of the embedded file should not change.
442         virtual void updateEmbeddedFile(EmbeddedFile const &) {}
443         /// Fill keys with BibTeX information
444         virtual void fillWithBibKeys(BiblioInfo &, InsetIterator const &) const {}
445         /// Update the counters of this inset and of its contents
446         virtual void updateLabels(ParIterator const &) {}
447
448         /// Updates the inset's dialog
449         virtual Buffer const * updateFrontend() const;
450
451 public:
452         /// returns LyX code associated with the inset. Used for TOC, ...)
453         virtual InsetCode lyxCode() const { return NO_CODE; }
454
455         /// -1: text mode, 1: math mode, 0 undecided
456         enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
457         /// return text or mathmode if that is possible to determine
458         virtual mode_type currentMode() const { return UNDECIDED_MODE; }
459         /// returns whether this inset is allowed in other insets of given mode
460         virtual bool allowedIn(mode_type) const { return true; }
461         /**
462          * Is this inset allowed within a font change?
463          *
464          * FIXME: noFontChange means currently that the font change is closed
465          * in LaTeX before the inset, and that the contents of the inset
466          * will be in default font. This should be changed so that the inset
467          * changes the font again.
468          */
469         virtual bool noFontChange() const { return false; }
470
471         /// set the change for the entire inset
472         virtual void setChange(Change const &) {}
473         /// accept the changes within the inset
474         virtual void acceptChanges(BufferParams const &) {};
475         /// reject the changes within the inset
476         virtual void rejectChanges(BufferParams const &) {};
477
478         ///
479         virtual Dimension const dimension(BufferView const &) const;
480         ///
481         int scroll() const { return 0; }
482         ///
483         virtual ColorCode backgroundColor() const;
484         ///
485         enum CollapseStatus {
486                 Collapsed,
487                 Open
488         };
489         ///
490         virtual void setStatus(Cursor &, CollapseStatus) {}
491         //
492         enum { TEXT_TO_INSET_OFFSET = 4 };
493
494 protected:
495         /// Constructor
496         explicit Inset() : buffer_(0) {}
497
498         /// replicate ourselves
499         friend class InsetList;
500         friend class MathAtom;
501         virtual Inset * clone() const = 0;
502
503         /** The real dispatcher.
504          *  Gets normally called from Cursor::dispatch(). Cursor::dispatch()
505          *  assumes the common case of 'LFUN handled, need update'.
506          *  This has to be overriden by calling Cursor::undispatched() or
507          *  Cursor::noUpdate() if appropriate.
508          *  If you need to call the dispatch method of some inset directly
509          *  you may have to explicitly request an update at that place. Don't
510          *  do it in doDispatch(), since that causes nested updates when
511          *  called from Cursor::dispatch(), and these can lead to crashes.
512          *  \sa getStatus
513          */
514         virtual void doDispatch(Cursor & cur, FuncRequest & cmd);
515
516         Buffer * buffer_;
517 };
518
519 } // namespace lyx
520
521 #endif