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