4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Alejandro Aguilar Sierra
9 * \author Lars Gullik Bjønnes
10 * \author Matthias Ettrich
12 * Full author contact details are available in file CREDITS.
18 #include "ColorCode.h"
19 #include "InsetCode.h"
20 #include "InsetLayout.h"
21 #include "LayoutEnums.h"
22 #include "OutputEnums.h"
24 #include "support/strfwd.h"
25 #include "support/types.h"
44 class InsetCollapsable;
58 class ParConstIterator;
66 namespace graphics { class PreviewLoader; }
69 /// returns the InsetCode corresponding to the \c name.
70 /// Eg, insetCode("branch") == BRANCH_CODE
71 InsetCode insetCode(std::string const & name);
72 /// returns the Inset name corresponding to the \c InsetCode.
73 /// Eg, insetName(BRANCH_CODE) == "branch"
74 std::string insetName(InsetCode);
75 /// returns the Inset name corresponding to the \c InsetCode.
76 /// Eg, insetDisplayName(BRANCH_CODE) == _("Branch")
77 docstring insetDisplayName(InsetCode);
79 static int const TOC_ENTRY_LENGTH = 120;
81 /// Common base class to all insets
83 // Do not add _any_ (non-static) data members as this would inflate
84 // everything storing large quantities of insets. Mathed e.g. would
91 ENTRY_DIRECTION_IGNORE,
92 ENTRY_DIRECTION_RIGHT,
96 typedef ptrdiff_t difference_type;
97 /// short of anything else reasonable
98 typedef size_t size_type;
99 /// type for cell indices
100 typedef size_t idx_type;
101 /// type for cursor positions
102 typedef ptrdiff_t pos_type;
103 /// type for row numbers
104 typedef size_t row_type;
105 /// type for column numbers
106 typedef size_t col_type;
108 /// virtual base class destructor
111 /// change associated Buffer
112 virtual void setBuffer(Buffer & buffer);
113 /// reset associated Buffer to null value
114 virtual void resetBuffer();
115 /// retrieve associated Buffer
117 Buffer const & buffer() const;
118 /// Returns true if buffer_ actually points to a Buffer that has
119 /// been loaded into LyX and is still open. Note that this will
120 /// always return false for cloned Buffers. If you want to allow
121 /// for the case of cloned Buffers, use isBufferValid().
122 bool isBufferLoaded() const;
123 /// Returns true if this is a loaded buffer or a cloned buffer.
124 bool isBufferValid() const;
126 /// initialize view for this inset.
128 * This is typically used after this inset is created interactively.
129 * Intented purpose is to sanitize internal state with regard to current
132 virtual void initView() {}
133 /// \return true if this inset is labeled.
134 virtual bool isLabeled() const { return false; }
136 /// identification as math inset
137 virtual InsetMath * asInsetMath() { return 0; }
138 /// identification as math inset
139 virtual InsetMath const * asInsetMath() const { return 0; }
140 /// true for 'math' math inset, but not for e.g. mbox
141 virtual bool inMathed() const { return false; }
142 /// is this inset based on the InsetText class?
143 virtual InsetText * asInsetText() { return 0; }
144 /// is this inset based on the InsetText class?
145 virtual InsetText const * asInsetText() const { return 0; }
146 /// is this inset based on the InsetCollapsable class?
147 virtual InsetCollapsable * asInsetCollapsable() { return 0; }
148 /// is this inset based on the InsetCollapsable class?
149 virtual InsetCollapsable const * asInsetCollapsable() const { return 0; }
150 /// is this inset based on the InsetTabular class?
151 virtual InsetTabular * asInsetTabular() { return 0; }
152 /// is this inset based on the InsetTabular class?
153 virtual InsetTabular const * asInsetTabular() const { return 0; }
154 /// is this inset based on the InsetCommand class?
155 virtual InsetCommand * asInsetCommand() { return 0; }
156 /// is this inset based on the InsetCommand class?
157 virtual InsetCommand const * asInsetCommand() const { return 0; }
158 /// is this inset based on the InsetArgument class?
159 virtual InsetArgument const * asInsetArgument() const { return nullptr; }
161 /// the real dispatcher
162 void dispatch(Cursor & cur, FuncRequest & cmd);
164 * \returns true if this function made a definitive decision on
165 * whether the inset wants to handle the request \p cmd or not.
166 * The result of this decision is put into \p status.
168 * Every request that is enabled in this method needs to be handled
169 * in doDispatch(). Normally we have a 1:1 relationship between the
170 * requests handled in getStatus() and doDispatch(), but there are
172 * - A request that is disabled in getStatus() does not need to
173 * appear in doDispatch(). It is guaranteed that doDispatch()
174 * is never called with this request.
175 * - A few requests are en- or disabled in Inset::getStatus().
176 * These need to be handled in the doDispatch() methods of the
177 * derived insets, since Inset::doDispatch() has not enough
178 * information to handle them.
179 * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
180 * are dispatched directly
182 virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
183 FuncStatus & status) const;
186 virtual void edit(Cursor & cur, bool front,
187 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
189 /// Note: this method must preserve the selection status. See:
190 /// https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg199001.html
191 virtual Inset * editXY(Cursor & cur, int x, int y);
193 /// compute the size of the object returned in dim
194 virtual void metrics(MetricsInfo & mi, Dimension & dim) const = 0;
195 /// draw inset and update (xo, yo)-cache
196 virtual void draw(PainterInfo & pi, int x, int y) const = 0;
197 /// draw inset selection if necessary
198 virtual void drawSelection(PainterInfo &, int, int) const {}
199 /// draw inset background if the inset has an own background and a
200 /// selection is drawn by drawSelection.
201 virtual void drawBackground(PainterInfo &, int, int) const;
203 virtual bool editing(BufferView const * bv) const;
205 virtual bool showInsetDialog(BufferView *) const;
207 /// draw two angular markers
208 void drawMarkers(PainterInfo & pi, int x, int y) const;
209 /// draw four angular markers
210 void drawMarkers2(PainterInfo & pi, int x, int y) const;
211 /// add space for markers
212 void metricsMarkers(Dimension & dim, int framesize = 1) const;
213 /// add space for markers
214 void metricsMarkers2(Dimension & dim, int framesize = 1) const;
215 /// draw inset decoration if necessary.
216 /// This can use \c drawMarkers() for example.
217 virtual void drawDecoration(PainterInfo &, int, int) const {}
219 /// last metrics computed for the inset
220 Dimension const dimension(BufferView const &) const;
221 /// last drawn position for 'important' insets
222 int xo(BufferView const & bv) const;
223 /// last drawn position for 'important' insets
224 int yo(BufferView const & bv) const;
225 /// do we cover screen position x/y?
226 bool covers(BufferView const & bv, int x, int y) const;
227 /// get the screen positions of the cursor (see note in Cursor.cpp)
228 virtual void cursorPos(BufferView const & bv,
229 CursorSlice const & sl, bool boundary, int & x, int & y) const;
231 /// Allow multiple blanks
232 virtual bool isFreeSpacing() const;
233 /// Don't eliminate empty paragraphs
234 virtual bool allowEmpty() const;
235 /// Force inset into LTR environment if surroundings are RTL
236 virtual bool forceLTR() const;
237 /// whether to include this inset in the strings generated for the TOC
238 virtual bool isInToc() const;
240 /// Where should we go when we press the up or down cursor key?
241 virtual bool idxUpDown(Cursor & cur, bool up) const;
242 /// Move one cell backwards
243 virtual bool idxBackward(Cursor &) const { return false; }
244 /// Move one cell forward
245 virtual bool idxForward(Cursor &) const { return false; }
247 /// Move to the next cell
248 virtual bool idxNext(Cursor &) const { return false; }
249 /// Move to the previous cell
250 virtual bool idxPrev(Cursor &) const { return false; }
252 /// Target pos when we enter the inset while moving forward
253 virtual bool idxFirst(Cursor &) const { return false; }
254 /// Target pos when we enter the inset while moving backwards
255 virtual bool idxLast(Cursor &) const { return false; }
257 /// Delete a cell and move cursor
258 virtual bool idxDelete(idx_type &) { return false; }
259 /// pulls cell after pressing erase
260 virtual void idxGlue(idx_type) {}
261 /// returns list of cell indices that are "between" from and to for
262 /// selection purposes
263 virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
265 /// to which column belongs a cell with a given index?
266 virtual col_type col(idx_type) const { return 0; }
267 /// to which row belongs a cell with a given index?
268 virtual row_type row(idx_type) const { return 0; }
269 /// cell index corresponding to row and column;
270 virtual idx_type index(row_type row, col_type col) const;
271 /// number of embedded cells
272 virtual size_t nargs() const { return 0; }
273 /// number of rows in gridlike structures
274 virtual size_t nrows() const { return 0; }
275 /// number of columns in gridlike structures
276 virtual size_t ncols() const { return 0; }
277 /// Is called when the cursor leaves this inset.
278 /// Returns true if cursor is now invalid, e.g. if former
279 /// insets in higher cursor slices of \c old do not exist
281 /// \c old is the old cursor, the last slice points to this.
282 /// \c cur is the new cursor. Use the update flags to cause a redraw.
283 virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
285 /// Is called when the cursor enters this inset.
286 /// Returns true if cursor is now invalid, e.g. if former
287 /// insets in higher cursor slices of \c old do not exist
289 /// \c cur is the new cursor, some slice points to this. Use the update
290 /// flags to cause a redraw.
291 virtual bool notifyCursorEnters(Cursor & /*cur*/)
293 /// is called when the mouse enters or leaves this inset
294 /// return true if this inset needs a repaint
295 virtual bool setMouseHover(BufferView const *, bool) const
297 /// return true if this inset is hovered (under mouse)
298 /// This is by now only used by mathed to draw corners
299 /// (Inset::drawMarkers() and Inset::drawMarkers2()).
300 /// Other insets do not have to redefine this function to
301 /// return the correct status of mouseHovered.
302 virtual bool mouseHovered(BufferView const *) const { return false; }
304 /// request "external features"
305 virtual void validate(LaTeXFeatures &) const {}
307 /// Validate LFUN_INSET_MODIFY argument.
308 virtual bool validateModifyArgument(docstring const &) const { return true; }
310 /// describe content if cursor inside
311 virtual void infoize(odocstream &) const {}
312 /// describe content if cursor behind
313 virtual void infoize2(odocstream &) const {}
315 enum { PLAINTEXT_NEWLINE = 10000 };
317 /// plain text output in ucs4 encoding
318 /// return the number of characters; in case of multiple lines of
319 /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
320 virtual int plaintext(odocstringstream &, OutputParams const &,
321 size_t max_length = INT_MAX) const = 0;
323 virtual int docbook(odocstream & os, OutputParams const &) const;
325 /// the inset is expected to write XHTML to the XHTMLStream
326 /// \return any "deferred" material that should be written outside the
327 /// normal stream, and which will in fact be written after the current
328 /// paragraph closes. this is appropriate e.g. for floats.
329 virtual docstring xhtml(XHTMLStream & xs, OutputParams const &) const;
331 /// Writes a string representation of the inset to the odocstream.
332 /// This one should be called when you want the whole contents of
334 virtual void toString(odocstream &) const {}
335 /// Appends a potentially abbreviated version of the inset to
336 /// \param str. Intended for use by the TOC.
337 virtual void forOutliner(docstring & str,
338 size_t const maxlen = TOC_ENTRY_LENGTH,
339 bool const shorten = true) const;
341 /// can the contents of the inset be edited on screen ?
342 // true for InsetCollapsables (not ButtonOnly) (not InsetInfo), InsetText
343 virtual bool editable() const;
344 /// has the Inset settings that can be modified in a dialog ?
345 virtual bool hasSettings() const;
346 /// can we go further down on mouse click?
347 // true for InsetCaption, InsetCollapsables (not ButtonOnly), InsetTabular
348 virtual bool descendable(BufferView const &) const { return false; }
349 /// is this an inset that can be moved into?
350 /// FIXME: merge with editable()
351 // true for InsetTabular & InsetText
352 virtual bool isActive() const { return nargs() > 0; }
353 /// can we click at the specified position ?
354 virtual bool clickable(BufferView const &, int, int) const { return false; }
355 /// Move one cell backwards
356 virtual bool allowsCaptionVariation(std::string const &) const { return false; }
357 // true for insets that have a table structure (InsetMathGrid, InsetTabular)
358 virtual bool isTable() const { return false; }
360 /// does this contain text that can be change track marked in DVI?
361 virtual bool canTrackChanges() const { return false; }
362 /// Will this inset paint its own change tracking status (in the parent
363 /// paragraph) or will it let RowPainter handle it?
364 virtual bool canPaintChange(BufferView const &) const { return false; }
365 /// return true if the inset should be removed automatically
366 virtual bool autoDelete() const;
368 /// Returns true if the inset supports completions.
369 virtual bool completionSupported(Cursor const &) const { return false; }
370 /// Returns true if the inset supports inline completions at the
371 /// cursor position. In this case the completion might be stored
372 /// in the BufferView's inlineCompletion property.
373 virtual bool inlineCompletionSupported(Cursor const & /*cur*/) const
375 /// Return true if the inline completion should be automatic.
376 virtual bool automaticInlineCompletion() const { return true; }
377 /// Return true if the popup completion should be automatic.
378 virtual bool automaticPopupCompletion() const { return true; }
379 /// Return true if the cursor should indicate a completion.
380 virtual bool showCompletionCursor() const { return true; }
381 /// Returns completion suggestions at cursor position. Return an
382 /// null pointer if no completion is a available or possible.
383 /// The caller is responsible to free the returned object!
384 virtual CompletionList const * createCompletionList(Cursor const &) const
386 /// Returns the completion prefix to filter the suggestions for completion.
387 /// This is only called if completionList returned a non-null list.
388 virtual docstring completionPrefix(Cursor const &) const;
389 /// Do a completion at the cursor position. Return true on success.
390 /// The completion does not contain the prefix. If finished is true, the
391 /// completion is final. If finished is false, completion might only be
392 /// a partial completion.
393 virtual bool insertCompletion(Cursor & /*cur*/,
394 docstring const & /*completion*/, bool /*finished*/)
396 /// Get the completion inset position and size
397 virtual void completionPosAndDim(Cursor const &, int & /*x*/, int & /*y*/,
398 Dimension & /*dim*/) const {}
400 /// returns true if the inset can hold an inset of given type
401 virtual bool insetAllowed(InsetCode) const { return false; }
402 /// should this inset use the empty layout by default rather than
403 /// the standard layout? (default: only if that is forced.)
404 virtual bool usePlainLayout() const { return forcePlainLayout(); }
405 /// if this inset has paragraphs should they be forced to use the
407 virtual bool forcePlainLayout(idx_type = 0) const { return false; }
408 /// if this inset has paragraphs should the user be allowed to
409 /// customize alignment, etc?
410 virtual bool allowParagraphCustomization(idx_type = 0) const
412 /// Is the width forced to some value?
413 virtual bool hasFixedWidth() const { return false; }
414 /// if this inset has paragraphs should they be forced to use a
415 /// local font language switch?
416 virtual bool forceLocalFontSwitch() const { return false; }
418 /// Is the content of this inset part of the output document?
419 virtual bool producesOutput() const { return true; }
420 /// Is the content of this inset part of the immediate (visible) text sequence?
421 virtual bool isPartOfTextSequence() const { return producesOutput(); }
423 /// \return Tool tip for this inset.
424 /// This default implementation returns an empty string. This can be
425 /// either plain text or Qt html, and formatToolTip will be called
426 /// on it before display in both cases.
427 virtual docstring toolTip(BufferView const & bv, int x, int y) const;
429 /// \return Context menu identifier. This function determines
430 /// whose Inset's menu should be shown for the given position.
431 virtual std::string contextMenu(BufferView const & bv, int x, int y) const;
433 /// \return Context menu identifier for this inset.
434 /// This default implementation returns an empty string.
435 virtual std::string contextMenuName() const;
438 virtual docstring layoutName() const;
440 virtual InsetLayout const & getLayout() const;
442 virtual bool isPassThru() const { return getLayout().isPassThru(); }
443 /// Is this inset's layout defined in the document's textclass?
444 bool undefined() const;
445 /// should this inset be handled like a normal character?
446 /// (a character can be a letter or punctuation)
447 virtual bool isChar() const { return false; }
448 /// is this equivalent to a letter?
449 /// (a letter is a character that is considered part of a word)
450 virtual bool isLetter() const { return false; }
451 /// is this equivalent to a space (which is BTW different from
452 /// a line separator)?
453 virtual bool isSpace() const { return false; }
454 /// does this inset try to use all available space (like \\hfill does)?
455 virtual bool isHfill() const { return false; }
464 /// should we have a non-filled line before this inset?
465 virtual DisplayType display() const { return Inline; }
466 /// indentation before this inset (only needed for displayed hull insets with fleqn option)
467 virtual int indent(BufferView const &) const { return 0; }
469 virtual LyXAlignment contentAlignment() const { return LYX_ALIGN_NONE; }
470 /// should we break lines after this inset?
471 virtual bool isLineSeparator() const { return false; }
472 /// should paragraph indendation be ommitted in any case?
473 virtual bool neverIndent() const { return false; }
474 /// dumps content to lyxerr
475 virtual void dump() const;
476 /// write inset in .lyx format
477 virtual void write(std::ostream &) const {}
478 /// read inset in .lyx format
479 virtual void read(Lexer &) {}
480 /** Export the inset to LaTeX.
481 * Don't use a temporary stringstream if the final output is
482 * supposed to go to a file.
483 * \sa Buffer::writeLaTeXSource for the reason.
485 virtual void latex(otexstream &, OutputParams const &) const {}
486 /// returns true to override begin and end inset in file
487 virtual bool directWrite() const;
489 virtual bool allowSpellCheck() const { return false; }
491 /// if this insets owns text cells (e.g. InsetText) return cell num
492 virtual Text * getText(int /*num*/) const { return 0; }
494 /** Adds a LaTeX snippet to the Preview Loader for transformation
495 * into a bitmap image. Does not start the laoding process.
497 * Most insets have no interest in this capability, so the method
500 virtual void addPreview(DocIterator const &,
501 graphics::PreviewLoader &) const {}
503 /** Classifies the unicode characters appearing in a math inset
504 * depending on whether they are to be translated as latex
505 * math/text commands or used as math symbols without translation.
507 * Only math insets have interest in this classification, so the
508 * method defaults to empty.
510 virtual void initUnicodeMath() const {}
512 /// Add an entry to the TocList
513 /// Pass a DocIterator that points at the paragraph containing
516 /// \param output_active : is the inset active or is it in an inactive
517 /// branch or a note?
519 /// \param utype : is the toc being generated for use by the output
522 /// \param tocbackend : where to add the toc information.
523 virtual void addToToc(DocIterator const & /* di */,
524 bool /* output_active */,
525 UpdateType /* utype*/,
526 TocBackend & /* tocbackend */) const {}
527 /// Collect BibTeX information
528 virtual void collectBibKeys(InsetIterator const &) const {}
529 /// Update the counters of this inset and of its contents.
530 /// The boolean indicates whether we are preparing for output, e.g.,
532 virtual void updateBuffer(ParIterator const &, UpdateType) {}
534 /// Updates the inset's dialog
535 virtual Buffer const * updateFrontend() const;
538 /// returns LyX code associated with the inset. Used for TOC, ...)
539 virtual InsetCode lyxCode() const { return NO_CODE; }
542 enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
543 /// return text or mathmode if that is possible to determine
544 virtual mode_type currentMode() const { return UNDECIDED_MODE; }
545 /// returns whether changing mode during latex export is forbidden
546 virtual bool lockedMode() const { return false; }
547 /// returns whether only ascii chars are allowed during latex export
548 virtual bool asciiOnly() const { return false; }
549 /// returns whether this inset is allowed in other insets of given mode
550 virtual bool allowedIn(mode_type) const { return true; }
552 * The font is inherited from the parent for LaTeX export if this
553 * method returns true. No open font changes are closed in front of
554 * the inset for LaTeX export, and the font is inherited for all other
555 * exports as well as on screen.
556 * If this method returns false all open font changes are closed in
557 * front of the inset for LaTeX export. The default font is used
558 * inside the inset for all exports and on screen.
560 virtual bool inheritFont() const { return true; }
562 * If this method returns true all explicitly set font attributes
563 * are reset during editing operations.
564 * For copy/paste operations the language is never changed, since
565 * the language of a given text never changes if the text is
566 * formatted differently, while other font attribues like size may
567 * need to change if the text is copied from one environment to
569 * If this method returns false no font attribute is reset.
570 * The default implementation returns true if the resetFont layout
571 * tag is set and otherwise the negation of inheritFont(),
572 * since inherited inset font attributes do not need to be changed,
573 * and non-inherited ones need to be set explicitly.
575 virtual bool resetFontEdit() const;
577 /// set the change for the entire inset
578 virtual void setChange(Change const &) {}
579 /// accept the changes within the inset
580 virtual void acceptChanges() {}
581 /// reject the changes within the inset
582 virtual void rejectChanges() {}
585 virtual ColorCode backgroundColor(PainterInfo const &) const;
587 virtual ColorCode labelColor() const;
589 enum { TEXT_TO_INSET_OFFSET = 4 };
591 /// Determine the action of backspace and delete: do we select instead of
592 /// deleting if not already selected?
593 virtual bool confirmDeletion() const { return false; }
597 Inset(Buffer * buf) : buffer_(buf) {}
598 Inset(Inset const &) : buffer_(0) {}
600 /// replicate ourselves
601 friend class InsetList;
602 friend class MathAtom;
603 virtual Inset * clone() const = 0;
605 /** The real dispatcher.
606 * Gets normally called from Cursor::dispatch(). Cursor::dispatch()
607 * assumes the common case of 'LFUN handled, need update'.
608 * This has to be overriden by calling Cursor::undispatched() or
609 * Cursor::noScreenUpdate() if appropriate.
610 * If you need to call the dispatch method of some inset directly
611 * you may have to explicitly request an update at that place. Don't
612 * do it in doDispatch(), since that causes nested updates when
613 * called from Cursor::dispatch(), and these can lead to crashes.
616 virtual void doDispatch(Cursor & cur, FuncRequest & cmd);