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