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 "LayoutEnums.h"
21 #include "OutputEnums.h"
22 #include "OutputParams.h"
25 #include "support/docstring.h"
26 #include "support/strfwd.h"
27 #include "support/types.h"
46 class InsetCollapsible;
67 namespace graphics { class PreviewLoader; }
69 namespace support {class FileNameList; }
71 /// returns the InsetCode corresponding to the \c name.
72 /// Eg, insetCode("branch") == BRANCH_CODE
73 InsetCode insetCode(std::string const & name);
74 /// returns the Inset name corresponding to the \c InsetCode.
75 /// Eg, insetName(BRANCH_CODE) == "branch"
76 std::string insetName(InsetCode);
77 /// returns the Inset name corresponding to the \c InsetCode.
78 /// Eg, insetDisplayName(BRANCH_CODE) == _("Branch")
79 docstring insetDisplayName(InsetCode);
81 static int const TOC_ENTRY_LENGTH = 120;
83 /// Common base class to all insets
85 // Do not add _any_ (non-static) data members as this would inflate
86 // everything storing large quantities of insets. Mathed e.g. would
93 ENTRY_DIRECTION_IGNORE,
94 ENTRY_DIRECTION_RIGHT,
98 /// virtual base class destructor
101 /// change associated Buffer
102 virtual void setBuffer(Buffer & buffer);
103 /// reset associated Buffer to null value
104 virtual void resetBuffer();
105 /// retrieve associated Buffer
107 Buffer const & buffer() const;
108 /// Returns true if buffer_ actually points to a Buffer that has
109 /// been loaded into LyX and is still open. Note that this will
110 /// always return false for cloned Buffers. If you want to allow
111 /// for the case of cloned Buffers, use isBufferValid().
112 bool isBufferLoaded() const;
113 /// Returns true if this is a loaded buffer or a cloned buffer.
114 bool isBufferValid() const;
116 /// initialize view for this inset.
118 * This is typically used after this inset is created interactively.
119 * Intended purpose is to sanitize internal state with regard to current
122 virtual void initView() {}
123 /// \return true if this inset is labeled.
124 virtual bool isLabeled() const { return false; }
126 /// identification as math inset
127 virtual InsetMath * asInsetMath() { return nullptr; }
128 /// identification as math inset
129 virtual InsetMath const * asInsetMath() const { return nullptr; }
130 /// true for 'math' math inset, but not for e.g. mbox
131 virtual bool inMathed() const { return false; }
132 /// is this inset based on the InsetText class?
133 virtual InsetText * asInsetText() { return nullptr; }
134 /// is this inset based on the InsetText class?
135 virtual InsetText const * asInsetText() const { return nullptr; }
136 /// is this inset based on the InsetCollapsible class?
137 virtual InsetCollapsible * asInsetCollapsible() { return nullptr; }
138 /// is this inset based on the InsetCollapsible class?
139 virtual InsetCollapsible const * asInsetCollapsible() const { return nullptr; }
140 /// is this inset based on the InsetTabular class?
141 virtual InsetTabular * asInsetTabular() { return nullptr; }
142 /// is this inset based on the InsetTabular class?
143 virtual InsetTabular const * asInsetTabular() const { return nullptr; }
144 /// is this inset based on the InsetCommand class?
145 virtual InsetCommand * asInsetCommand() { return nullptr; }
146 /// is this inset based on the InsetCommand class?
147 virtual InsetCommand const * asInsetCommand() const { return nullptr; }
148 /// is this inset based on the InsetArgument class?
149 virtual InsetArgument const * asInsetArgument() const { return nullptr; }
150 /// is this inset based on the InsetIndex class?
151 virtual InsetIndex const * asInsetIndex() const { return nullptr; }
152 /// is this inset based on the InsetGraphics class?
153 virtual InsetGraphics * asInsetGraphics() { return nullptr; }
154 /// is this inset based on the InsetGraphics class?
155 virtual InsetGraphics const * asInsetGraphics() const { return nullptr; }
157 /// the real dispatcher
158 void dispatch(Cursor & cur, FuncRequest & cmd);
160 * \returns true if this function made a definitive decision on
161 * whether the inset wants to handle the request \p cmd or not.
162 * The result of this decision is put into \p status.
164 * Every request that is enabled in this method needs to be handled
165 * in doDispatch(). Normally we have a 1:1 relationship between the
166 * requests handled in getStatus() and doDispatch(), but there are
168 * - A request that is disabled in getStatus() does not need to
169 * appear in doDispatch(). It is guaranteed that doDispatch()
170 * is never called with this request.
171 * - A few requests are en- or disabled in Inset::getStatus().
172 * These need to be handled in the doDispatch() methods of the
173 * derived insets, since Inset::doDispatch() has not enough
174 * information to handle them.
175 * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
176 * are dispatched directly
178 virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
179 FuncStatus & status) const;
182 virtual void edit(Cursor & cur, bool front,
183 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
184 /// sets cursor recursively descending into nested editable insets
186 \return the inset pointer if x,y is covering that inset
187 \param x,y are absolute screen coordinates.
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 /// The default margin inside text insets
194 static int textOffset(BufferView const *) { return 4; }
196 virtual int topOffset(BufferView const *bv) const { return textOffset(bv); }
198 virtual int bottomOffset(BufferView const *bv) const { return textOffset(bv); }
200 virtual int leftOffset(BufferView const *bv) const { return textOffset(bv); }
202 virtual int rightOffset(BufferView const *bv) const { return textOffset(bv); }
204 /// compute the size of the object returned in dim
205 virtual void metrics(MetricsInfo & mi, Dimension & dim) const = 0;
206 /// draw inset and update (xo, yo)-cache
207 virtual void draw(PainterInfo & pi, int x, int y) const = 0;
208 /// draw inset selection if necessary
209 virtual void drawSelection(PainterInfo &, int, int) const {}
210 /// draw inset background if the inset has an own background and a
211 /// selection is drawn by drawSelection.
212 virtual void drawBackground(PainterInfo &, int, int) const;
214 virtual bool editing(BufferView const * bv) const;
216 virtual bool showInsetDialog(BufferView *) const;
218 /// draw two angular markers
219 virtual void drawMarkers(PainterInfo & pi, int x, int y) const;
220 /// add space for markers
221 void metricsMarkers(Dimension & dim, int framesize = 1) const;
222 /// add space for markers
223 void metricsMarkers2(Dimension & dim, int framesize = 1) const;
224 /// draw inset decoration if necessary.
225 /// This can use \c drawMarkers() for example.
226 virtual void drawDecoration(PainterInfo &, int, int) const {}
228 /// last metrics computed for the inset
229 Dimension const dimension(BufferView const &) const;
230 /// last drawn position for 'important' insets
231 int xo(BufferView const & bv) const;
232 /// last drawn position for 'important' insets
233 int yo(BufferView const & bv) const;
234 /// do we cover screen position x/y?
235 bool covers(BufferView const & bv, int x, int y) const;
236 /// get the screen positions of the cursor (see note in Cursor.cpp)
237 virtual void cursorPos(BufferView const & bv,
238 CursorSlice const & sl, bool boundary, int & x, int & y) const;
241 virtual docstring layoutName() const;
243 virtual InsetLayout const & getLayout() const;
245 virtual bool isPassThru() const;
246 /// Allow multiple blanks
247 virtual bool isFreeSpacing() const;
248 /// Don't eliminate empty paragraphs
249 virtual bool allowEmpty() const;
250 /// Force inset into LTR environment if surroundings are RTL
251 virtual bool forceLTR(OutputParams const &) const;
252 /// whether to include this inset in the strings generated for the TOC
253 virtual bool isInToc() const;
255 virtual FontInfo getFont() const;
257 virtual FontInfo getLabelfont() const;
259 /// Where should we go when we press the up or down cursor key?
260 virtual bool idxUpDown(Cursor & cur, bool up) const;
261 /// Move one cell backwards
262 virtual bool idxBackward(Cursor &) const { return false; }
263 /// Move one cell forward
264 virtual bool idxForward(Cursor &) const { return false; }
266 /// Move to the next cell
267 virtual bool idxNext(Cursor &) const { return false; }
268 /// Move to the previous cell
269 virtual bool idxPrev(Cursor &) const { return false; }
271 /// Target pos when we enter the inset while moving forward
272 virtual bool idxFirst(Cursor &) const { return false; }
273 /// Target pos when we enter the inset while moving backwards
274 virtual bool idxLast(Cursor &) const { return false; }
276 /// Delete a cell and move cursor
277 virtual bool idxDelete(idx_type &) { return false; }
278 /// pulls cell after pressing erase
279 virtual void idxGlue(idx_type) {}
280 /// returns list of cell indices that are "between" from and to for
281 /// selection purposes
282 virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
284 /// to which column belongs a cell with a given index?
285 virtual col_type col(idx_type) const { return 0; }
286 /// to which row belongs a cell with a given index?
287 virtual row_type row(idx_type) const { return 0; }
288 /// cell index corresponding to row and column;
289 virtual idx_type index(row_type row, col_type col) const;
290 /// number of embedded cells
291 virtual size_t nargs() const { return 0; }
292 /// number of rows in gridlike structures
293 virtual size_t nrows() const { return 0; }
294 /// number of columns in gridlike structures
295 virtual size_t ncols() const { return 0; }
296 /// Is called when the cursor leaves this inset.
297 /// Returns true if cursor is now invalid, e.g. if former
298 /// insets in higher cursor slices of \c old do not exist
300 /// \c old is the old cursor, the last slice points to this.
301 /// \c cur is the new cursor. Use the update flags to cause a redraw.
302 virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
304 /// Is called when the cursor enters this inset.
305 /// Returns true if cursor is now invalid, e.g. if former
306 /// insets in higher cursor slices of \c old do not exist
308 /// \c cur is the new cursor, some slice points to this. Use the update
309 /// flags to cause a redraw.
310 virtual bool notifyCursorEnters(Cursor & /*cur*/)
312 /// is called when the mouse enters or leaves this inset
313 /// return true if this inset needs a repaint
314 virtual bool setMouseHover(BufferView const *, bool) const
316 /// return true if this inset is hovered (under mouse)
317 /// This is by now only used by mathed to draw corners
318 /// (Inset::drawMarkers() and Inset::drawMarkers2()).
319 /// Other insets do not have to redefine this function to
320 /// return the correct status of mouseHovered.
321 virtual bool mouseHovered(BufferView const *) const { return false; }
323 /// request "external features"
324 virtual void validate(LaTeXFeatures &) const {}
326 /// Validate LFUN_INSET_MODIFY argument.
327 virtual bool validateModifyArgument(docstring const &) const { return true; }
329 /// describe content if cursor inside
330 virtual void infoize(odocstream &) const {}
331 /// describe content if cursor behind
332 virtual void infoize2(odocstream &) const {}
334 enum { PLAINTEXT_NEWLINE = 10000 };
336 /// plain text output in ucs4 encoding
337 /// return the number of characters; in case of multiple lines of
338 /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
339 virtual int plaintext(odocstringstream &, OutputParams const &,
340 size_t max_length = INT_MAX) const = 0;
342 virtual void docbook(XMLStream &, OutputParams const &) const;
344 /// the inset is expected to write XHTML to the XMLStream
345 /// \return any "deferred" material that should be written outside the
346 /// normal stream, and which will in fact be written after the current
347 /// paragraph closes. this is appropriate e.g. for floats.
348 virtual docstring xhtml(XMLStream &, OutputParams const &) const;
350 /// Writes a string representation of the inset to the odocstream.
351 /// This one should be called when you want the whole contents of
353 virtual void toString(odocstream &) const {}
354 /// Appends a potentially abbreviated version of the inset to
355 /// \param str. Intended for use by the TOC.
356 virtual void forOutliner(docstring & str,
357 size_t const maxlen = TOC_ENTRY_LENGTH,
358 bool const shorten = true) const;
360 /// Can a cursor be put in there ?
361 /// Forced to false for insets that have hidden contents, like
362 /// InsetMathCommand and InsetInfo.
363 virtual bool isActive() const { return nargs() > 0; }
364 /// can the contents of the inset be edited on screen ?
365 // equivalent to isActive except for closed InsetCollapsible
366 virtual bool editable() const;
367 /// has the Inset settings that can be modified in a dialog ?
368 virtual bool hasSettings() const;
369 /// can we go further down on mouse click?
370 /// true for InsetCaption, InsetCollapsibles (not ButtonOnly), InsetTabular
371 virtual bool descendable(BufferView const &) const { return false; }
372 /// can we click at the specified position ?
373 virtual bool clickable(BufferView const &, int, int) const { return false; }
374 /// Move one cell backwards
375 virtual bool allowsCaptionVariation(std::string const &) const { return false; }
376 // true for insets that have a table structure (InsetMathGrid, InsetTabular)
377 virtual bool isTable() const { return false; }
379 /// does this contain text that can be change track marked in DVI?
380 virtual bool canTrackChanges() const { return false; }
381 /// Will this inset paint its own change tracking status (in the parent
382 /// paragraph) or will it let RowPainter handle it?
383 virtual bool canPaintChange(BufferView const &) const { return false; }
384 /// return true if the inset should be removed automatically
385 virtual bool autoDelete() const;
387 /// Returns true if the inset supports completions.
388 virtual bool completionSupported(Cursor const &) const { return false; }
389 /// Returns true if the inset supports inline completions at the
390 /// cursor position. In this case the completion might be stored
391 /// in the BufferView's inlineCompletion property.
392 virtual bool inlineCompletionSupported(Cursor const & /*cur*/) const
394 /// Return true if the inline completion should be automatic.
395 virtual bool automaticInlineCompletion() const { return true; }
396 /// Return true if the popup completion should be automatic.
397 virtual bool automaticPopupCompletion() const { return true; }
398 /// Return true if the cursor should indicate a completion.
399 virtual bool showCompletionCursor() const { return true; }
400 /// Returns completion suggestions at cursor position. Return an
401 /// null pointer if no completion is a available or possible.
402 /// The caller is responsible to free the returned object!
403 virtual CompletionList const * createCompletionList(Cursor const &) const
405 /// Returns the completion prefix to filter the suggestions for completion.
406 /// This is only called if completionList returned a non-null list.
407 virtual docstring completionPrefix(Cursor const &) const;
408 /// Do a completion at the cursor position. Return true on success. Handles undo.
409 /// The completion does not contain the prefix.
410 /// If finished is true, the completion is final, otherwise it
411 /// might be only partial. (only useful for mathed)
412 virtual bool insertCompletion(Cursor & /*cur*/,
413 docstring const & /*completion*/, bool /*finished*/)
415 /// Get the completion inset position and size
416 virtual void completionPosAndDim(Cursor const &, int & /*x*/, int & /*y*/,
417 Dimension & /*dim*/) const {}
419 /// returns true if the inset can hold an inset of given type
420 virtual bool insetAllowed(InsetCode) const { return false; }
421 /// should this inset use the empty layout by default rather than
422 /// the standard layout? (default: only if that is forced.)
423 virtual bool usePlainLayout() const { return forcePlainLayout(); }
424 /// if this inset has paragraphs should they be forced to use the
426 virtual bool forcePlainLayout(idx_type = 0) const { return false; }
427 /// if this inset has paragraphs should the user be allowed to
428 /// customize alignment, etc?
429 virtual bool allowParagraphCustomization(idx_type = 0) const
431 /// Is the width forced to some value?
432 virtual bool hasFixedWidth() const { return false; }
433 /// if this inset has paragraphs should they be forced to use a
434 /// local font language switch?
435 virtual bool forceLocalFontSwitch() const { return false; }
436 /// if this inset has paragraphs should they be forced to use a
437 /// font language switch that switches paragraph directions
438 /// (relevant with polyglossia only)?
439 virtual bool forceParDirectionSwitch() const { return false; }
440 /// Does the inset force a specific encoding?
441 virtual Encoding const * forcedEncoding(Encoding const *, Encoding const *) const
445 /// Is the content of this inset part of the output document?
446 virtual bool producesOutput() const { return true; }
447 /// Is the content of this inset part of the immediate (visible) text sequence?
448 virtual bool isPartOfTextSequence() const { return producesOutput(); }
450 /// \return Tool tip for this inset.
451 /// This default implementation returns an empty string. This can be
452 /// either plain text or Qt html, and formatToolTip will be called
453 /// on it before display in both cases.
454 virtual docstring toolTip(BufferView const & bv, int x, int y) const;
456 /// \return Context menu identifier. This function determines
457 /// whose Inset's menu should be shown for the given position.
458 virtual std::string contextMenu(BufferView const & bv, int x, int y) const;
460 /// \return Context menu identifier for this inset.
461 /// This default implementation returns an empty string.
462 virtual std::string contextMenuName() const;
464 /// Is this inset embedded in a title?
465 virtual bool isInTitle() const { return false; }
466 /// Is this inset's layout defined in the document's textclass?
467 bool undefined() const;
468 /// should this inset be handled like a normal character?
469 /// (a character can be a letter or punctuation)
470 virtual bool isChar() const { return false; }
471 /// is this equivalent to a letter?
472 /// (a letter is a character that is considered part of a word)
473 virtual bool isLetter() const { return false; }
474 /// is this equivalent to a space (which is BTW different from
475 /// a line separator)?
476 virtual bool isSpace() const { return false; }
477 /// returns chars, words if the inset is equivalent to such, otherwise
478 /// (0,0), which should be interpreted as 'false'
479 virtual std::pair<int, int> isWords() const { return std::pair<int,int>(0, 0); }
480 /// does this inset try to use all available space (like \\hfill does)?
481 virtual bool isHfill() const { return false; }
483 virtual CtObject getCtObject(OutputParams const &) const;
485 // properties with respect to row breaking (made of RowFLag enumerators)
486 virtual int rowFlags() const { return Inline; }
487 /// indentation before this inset (only needed for displayed hull insets with fleqn option)
488 virtual int indent(BufferView const &) const { return 0; }
490 virtual LyXAlignment contentAlignment() const { return LYX_ALIGN_NONE; }
491 /// should we break lines after this inset?
492 virtual bool isLineSeparator() const { return false; }
493 /// should paragraph indentation be omitted in any case?
494 virtual bool neverIndent() const { return false; }
495 /// dumps content to lyxerr
496 virtual void dump() const;
497 /// write inset in .lyx format
498 virtual void write(std::ostream &) const {}
499 /// read inset in .lyx format
500 virtual void read(Lexer &) {}
501 /** Export the inset to LaTeX.
502 * Don't use a temporary stringstream if the final output is
503 * supposed to go to a file.
504 * \sa Buffer::writeLaTeXSource for the reason.
506 virtual void latex(otexstream &, OutputParams const &) const {}
507 /// returns true to override begin and end inset in file
508 virtual bool directWrite() const;
510 virtual bool allowSpellCheck() const { return false; }
512 /// if this insets owns text cells (e.g. InsetText) return cell idx
513 virtual Text * getText(int /*idx*/) const { return 0; }
515 /** Adds a LaTeX snippet to the Preview Loader for transformation
516 * into a bitmap image. Does not start the loading process.
518 * Most insets have no interest in this capability, so the method
521 virtual void addPreview(DocIterator const &,
522 graphics::PreviewLoader &) const {}
524 /** Classifies the unicode characters appearing in a math inset
525 * depending on whether they are to be translated as latex
526 * math/text commands or used as math symbols without translation.
528 * Only math insets have interest in this classification, so the
529 * method defaults to empty.
531 virtual void initUnicodeMath() const {}
533 /// Add an entry to the TocList
534 /// Pass a DocIterator that points at the paragraph containing
537 /// \param output_active : is the inset active or is it in an inactive
538 /// branch or a note?
540 /// \param utype : is the toc being generated for use by the output
543 /// \param tocbackend : where to add the toc information.
544 virtual void addToToc(DocIterator const & /* di */,
545 bool /* output_active */,
546 UpdateType /* utype*/,
547 TocBackend & /* tocbackend */) const {}
548 /// Collect BibTeX information
549 virtual void collectBibKeys(InsetIterator const &, support::FileNameList &) const {}
550 /// Update the counters of this inset and of its contents.
551 /// \param utype indicates whether we are preparing for output, e.g., of XHTML.
552 /// \param deleted indicates whethe rthe inset is deleted.
553 virtual void updateBuffer(ParIterator const &, UpdateType /*utype*/, bool /*deleted*/) {}
555 /// Updates the inset's dialog
556 virtual Buffer const * updateFrontend() const;
559 /// returns LyX code associated with the inset. Used for TOC, ...)
560 virtual InsetCode lyxCode() const { return NO_CODE; }
563 enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
564 /// return text or mathmode if that is possible to determine
565 virtual mode_type currentMode() const { return UNDECIDED_MODE; }
566 /// returns whether changing mode during latex export is forbidden
567 virtual bool lockedMode() const { return false; }
568 /// returns whether only ascii chars are allowed during latex export
569 virtual bool asciiOnly() const { return false; }
570 /// returns whether this inset is allowed in other insets of given mode
571 virtual bool allowedIn(mode_type) const { return true; }
572 /// returns whether paragraph breaks can occur inside this inset
573 virtual bool allowMultiPar() const { return false; }
575 * The font inside the inset is inherited from the parent for
576 * LaTeX export if this method returns true, as well as on screen.
577 * Otherwise the document default font is used.
579 virtual bool inheritFont() const { return true; }
581 * If this method returns true all explicitly set font attributes
582 * are reset during editing operations.
583 * For copy/paste operations the language is never changed, since
584 * the language of a given text never changes if the text is
585 * formatted differently, while other font attributes like size may
586 * need to change if the text is copied from one environment to
588 * If this method returns false no font attribute is reset.
589 * The default implementation returns true if the resetFont layout
590 * tag is set and otherwise the negation of inheritFont(),
591 * since inherited inset font attributes do not need to be changed,
592 * and non-inherited ones need to be set explicitly.
594 virtual bool resetFontEdit() const;
596 /// does the inset contain changes ?
597 virtual bool isChanged() const { return false; }
598 /// set the change for the entire inset
599 virtual void setChange(Change const &) {}
600 /// accept the changes within the inset
601 virtual void acceptChanges() {}
602 /// reject the changes within the inset
603 virtual void rejectChanges() {}
606 virtual bool needsCProtection(bool const, bool const) const { return false; }
609 virtual ColorCode backgroundColor(PainterInfo const &) const;
611 virtual ColorCode labelColor() const;
613 /// Determine the action of backspace and delete: do we select instead of
614 /// deleting if not already selected?
615 virtual bool confirmDeletion() const { return false; }
619 Inset(Buffer * buf) : buffer_(buf) {}
620 Inset(Inset const &) : buffer_(0) {}
622 /// replicate ourselves
623 friend class InsetList;
624 friend class MathAtom;
625 virtual Inset * clone() const = 0;
627 /** The real dispatcher.
628 * Gets normally called from Cursor::dispatch(). Cursor::dispatch()
629 * assumes the common case of 'LFUN handled, need update'.
630 * This has to be overridden by calling Cursor::undispatched() or
631 * Cursor::noScreenUpdate() if appropriate.
632 * If you need to call the dispatch method of some inset directly
633 * you may have to explicitly request an update at that place. Don't
634 * do it in doDispatch(), since that causes nested updates when
635 * called from Cursor::dispatch(), and these can lead to crashes.
638 virtual void doDispatch(Cursor & cur, FuncRequest & cmd);