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