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