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"
26 #include "support/FileNameList.h"
46 class InsetCollapsible;
61 class ParConstIterator;
69 namespace graphics { class PreviewLoader; }
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 typedef ptrdiff_t difference_type;
100 /// short of anything else reasonable
101 typedef size_t size_type;
102 /// type for cell indices
103 typedef size_t idx_type;
104 /// type for cursor positions
105 typedef ptrdiff_t pos_type;
106 /// type for row numbers
107 typedef size_t row_type;
108 /// type for column numbers
109 typedef size_t col_type;
111 /// virtual base class destructor
114 /// change associated Buffer
115 virtual void setBuffer(Buffer & buffer);
116 /// reset associated Buffer to null value
117 virtual void resetBuffer();
118 /// retrieve associated Buffer
120 Buffer const & buffer() const;
121 /// Returns true if buffer_ actually points to a Buffer that has
122 /// been loaded into LyX and is still open. Note that this will
123 /// always return false for cloned Buffers. If you want to allow
124 /// for the case of cloned Buffers, use isBufferValid().
125 bool isBufferLoaded() const;
126 /// Returns true if this is a loaded buffer or a cloned buffer.
127 bool isBufferValid() const;
129 /// initialize view for this inset.
131 * This is typically used after this inset is created interactively.
132 * Intented purpose is to sanitize internal state with regard to current
135 virtual void initView() {}
136 /// \return true if this inset is labeled.
137 virtual bool isLabeled() const { return false; }
139 /// identification as math inset
140 virtual InsetMath * asInsetMath() { return 0; }
141 /// identification as math inset
142 virtual InsetMath const * asInsetMath() const { return 0; }
143 /// true for 'math' math inset, but not for e.g. mbox
144 virtual bool inMathed() const { return false; }
145 /// is this inset based on the InsetText class?
146 virtual InsetText * asInsetText() { return 0; }
147 /// is this inset based on the InsetText class?
148 virtual InsetText const * asInsetText() const { return 0; }
149 /// is this inset based on the InsetCollapsible class?
150 virtual InsetCollapsible * asInsetCollapsible() { return 0; }
151 /// is this inset based on the InsetCollapsible class?
152 virtual InsetCollapsible const * asInsetCollapsible() const { return 0; }
153 /// is this inset based on the InsetTabular class?
154 virtual InsetTabular * asInsetTabular() { return 0; }
155 /// is this inset based on the InsetTabular class?
156 virtual InsetTabular const * asInsetTabular() const { return 0; }
157 /// is this inset based on the InsetCommand class?
158 virtual InsetCommand * asInsetCommand() { return 0; }
159 /// is this inset based on the InsetCommand class?
160 virtual InsetCommand const * asInsetCommand() const { return 0; }
161 /// is this inset based on the InsetArgument class?
162 virtual InsetArgument const * asInsetArgument() const { return nullptr; }
163 /// is this inset based on the InsetGraphics class?
164 virtual InsetGraphics * asInsetGraphics() { return 0; }
165 /// is this inset based on the InsetGraphics class?
166 virtual InsetGraphics const * asInsetGraphics() const { return 0; }
168 /// the real dispatcher
169 void dispatch(Cursor & cur, FuncRequest & cmd);
171 * \returns true if this function made a definitive decision on
172 * whether the inset wants to handle the request \p cmd or not.
173 * The result of this decision is put into \p status.
175 * Every request that is enabled in this method needs to be handled
176 * in doDispatch(). Normally we have a 1:1 relationship between the
177 * requests handled in getStatus() and doDispatch(), but there are
179 * - A request that is disabled in getStatus() does not need to
180 * appear in doDispatch(). It is guaranteed that doDispatch()
181 * is never called with this request.
182 * - A few requests are en- or disabled in Inset::getStatus().
183 * These need to be handled in the doDispatch() methods of the
184 * derived insets, since Inset::doDispatch() has not enough
185 * information to handle them.
186 * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
187 * are dispatched directly
189 virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
190 FuncStatus & status) const;
193 virtual void edit(Cursor & cur, bool front,
194 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
195 /// sets cursor recursively descending into nested editable insets
197 \return the inset pointer if x,y is covering that inset
198 \param x,y are absolute screen coordinates.
200 /// Note: this method must preserve the selection status. See:
201 /// https://www.mail-archive.com/lyx-devel@lists.lyx.org/msg199001.html
202 virtual Inset * editXY(Cursor & cur, int x, int y);
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;
240 /// Allow multiple blanks
241 virtual bool isFreeSpacing() const;
242 /// Don't eliminate empty paragraphs
243 virtual bool allowEmpty() const;
244 /// Force inset into LTR environment if surroundings are RTL
245 virtual bool forceLTR(OutputParams const &) const;
246 /// whether to include this inset in the strings generated for the TOC
247 virtual bool isInToc() const;
249 /// Where should we go when we press the up or down cursor key?
250 virtual bool idxUpDown(Cursor & cur, bool up) const;
251 /// Move one cell backwards
252 virtual bool idxBackward(Cursor &) const { return false; }
253 /// Move one cell forward
254 virtual bool idxForward(Cursor &) const { return false; }
256 /// Move to the next cell
257 virtual bool idxNext(Cursor &) const { return false; }
258 /// Move to the previous cell
259 virtual bool idxPrev(Cursor &) const { return false; }
261 /// Target pos when we enter the inset while moving forward
262 virtual bool idxFirst(Cursor &) const { return false; }
263 /// Target pos when we enter the inset while moving backwards
264 virtual bool idxLast(Cursor &) const { return false; }
266 /// Delete a cell and move cursor
267 virtual bool idxDelete(idx_type &) { return false; }
268 /// pulls cell after pressing erase
269 virtual void idxGlue(idx_type) {}
270 /// returns list of cell indices that are "between" from and to for
271 /// selection purposes
272 virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
274 /// to which column belongs a cell with a given index?
275 virtual col_type col(idx_type) const { return 0; }
276 /// to which row belongs a cell with a given index?
277 virtual row_type row(idx_type) const { return 0; }
278 /// cell index corresponding to row and column;
279 virtual idx_type index(row_type row, col_type col) const;
280 /// number of embedded cells
281 virtual size_t nargs() const { return 0; }
282 /// number of rows in gridlike structures
283 virtual size_t nrows() const { return 0; }
284 /// number of columns in gridlike structures
285 virtual size_t ncols() const { return 0; }
286 /// Is called when the cursor leaves this inset.
287 /// Returns true if cursor is now invalid, e.g. if former
288 /// insets in higher cursor slices of \c old do not exist
290 /// \c old is the old cursor, the last slice points to this.
291 /// \c cur is the new cursor. Use the update flags to cause a redraw.
292 virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
294 /// Is called when the cursor enters this inset.
295 /// Returns true if cursor is now invalid, e.g. if former
296 /// insets in higher cursor slices of \c old do not exist
298 /// \c cur is the new cursor, some slice points to this. Use the update
299 /// flags to cause a redraw.
300 virtual bool notifyCursorEnters(Cursor & /*cur*/)
302 /// is called when the mouse enters or leaves this inset
303 /// return true if this inset needs a repaint
304 virtual bool setMouseHover(BufferView const *, bool) const
306 /// return true if this inset is hovered (under mouse)
307 /// This is by now only used by mathed to draw corners
308 /// (Inset::drawMarkers() and Inset::drawMarkers2()).
309 /// Other insets do not have to redefine this function to
310 /// return the correct status of mouseHovered.
311 virtual bool mouseHovered(BufferView const *) const { return false; }
313 /// request "external features"
314 virtual void validate(LaTeXFeatures &) const {}
316 /// Validate LFUN_INSET_MODIFY argument.
317 virtual bool validateModifyArgument(docstring const &) const { return true; }
319 /// describe content if cursor inside
320 virtual void infoize(odocstream &) const {}
321 /// describe content if cursor behind
322 virtual void infoize2(odocstream &) const {}
324 enum { PLAINTEXT_NEWLINE = 10000 };
326 /// plain text output in ucs4 encoding
327 /// return the number of characters; in case of multiple lines of
328 /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
329 virtual int plaintext(odocstringstream &, OutputParams const &,
330 size_t max_length = INT_MAX) const = 0;
332 virtual int docbook(odocstream & os, OutputParams const &) const;
334 /// the inset is expected to write XHTML to the XHTMLStream
335 /// \return any "deferred" material that should be written outside the
336 /// normal stream, and which will in fact be written after the current
337 /// paragraph closes. this is appropriate e.g. for floats.
338 virtual docstring xhtml(XHTMLStream & xs, OutputParams const &) const;
340 /// Writes a string representation of the inset to the odocstream.
341 /// This one should be called when you want the whole contents of
343 virtual void toString(odocstream &) const {}
344 /// Appends a potentially abbreviated version of the inset to
345 /// \param str. Intended for use by the TOC.
346 virtual void forOutliner(docstring & str,
347 size_t const maxlen = TOC_ENTRY_LENGTH,
348 bool const shorten = true) const;
350 /// Can a cursor be put in there ?
351 /// Forced to false for insets that have hidden contents, like
352 /// InsetMathCommand and InsetInfo.
353 virtual bool isActive() const { return nargs() > 0; }
354 /// can the contents of the inset be edited on screen ?
355 // equivalent to isActive except for closed InsetCollapsible
356 virtual bool editable() const;
357 /// has the Inset settings that can be modified in a dialog ?
358 virtual bool hasSettings() const;
359 /// can we go further down on mouse click?
360 /// true for InsetCaption, InsetCollapsibles (not ButtonOnly), InsetTabular
361 virtual bool descendable(BufferView const &) const { return false; }
362 /// can we click at the specified position ?
363 virtual bool clickable(BufferView const &, int, int) const { return false; }
364 /// Move one cell backwards
365 virtual bool allowsCaptionVariation(std::string const &) const { return false; }
366 // true for insets that have a table structure (InsetMathGrid, InsetTabular)
367 virtual bool isTable() const { return false; }
369 /// does this contain text that can be change track marked in DVI?
370 virtual bool canTrackChanges() const { return false; }
371 /// Will this inset paint its own change tracking status (in the parent
372 /// paragraph) or will it let RowPainter handle it?
373 virtual bool canPaintChange(BufferView const &) const { return false; }
374 /// return true if the inset should be removed automatically
375 virtual bool autoDelete() const;
377 /// Returns true if the inset supports completions.
378 virtual bool completionSupported(Cursor const &) const { return false; }
379 /// Returns true if the inset supports inline completions at the
380 /// cursor position. In this case the completion might be stored
381 /// in the BufferView's inlineCompletion property.
382 virtual bool inlineCompletionSupported(Cursor const & /*cur*/) const
384 /// Return true if the inline completion should be automatic.
385 virtual bool automaticInlineCompletion() const { return true; }
386 /// Return true if the popup completion should be automatic.
387 virtual bool automaticPopupCompletion() const { return true; }
388 /// Return true if the cursor should indicate a completion.
389 virtual bool showCompletionCursor() const { return true; }
390 /// Returns completion suggestions at cursor position. Return an
391 /// null pointer if no completion is a available or possible.
392 /// The caller is responsible to free the returned object!
393 virtual CompletionList const * createCompletionList(Cursor const &) const
395 /// Returns the completion prefix to filter the suggestions for completion.
396 /// This is only called if completionList returned a non-null list.
397 virtual docstring completionPrefix(Cursor const &) const;
398 /// Do a completion at the cursor position. Return true on success.
399 /// The completion does not contain the prefix. If finished is true, the
400 /// completion is final. If finished is false, completion might only be
401 /// a partial completion.
402 virtual bool insertCompletion(Cursor & /*cur*/,
403 docstring const & /*completion*/, bool /*finished*/)
405 /// Get the completion inset position and size
406 virtual void completionPosAndDim(Cursor const &, int & /*x*/, int & /*y*/,
407 Dimension & /*dim*/) const {}
409 /// returns true if the inset can hold an inset of given type
410 virtual bool insetAllowed(InsetCode) const { return false; }
411 /// should this inset use the empty layout by default rather than
412 /// the standard layout? (default: only if that is forced.)
413 virtual bool usePlainLayout() const { return forcePlainLayout(); }
414 /// if this inset has paragraphs should they be forced to use the
416 virtual bool forcePlainLayout(idx_type = 0) const { return false; }
417 /// if this inset has paragraphs should the user be allowed to
418 /// customize alignment, etc?
419 virtual bool allowParagraphCustomization(idx_type = 0) const
421 /// Is the width forced to some value?
422 virtual bool hasFixedWidth() const { return false; }
423 /// if this inset has paragraphs should they be forced to use a
424 /// local font language switch?
425 virtual bool forceLocalFontSwitch() const { return false; }
426 /// if this inset has paragraphs should they be forced to use a
427 /// font language switch that switches paragraph directions
428 /// (relevant with polyglossia only)?
429 virtual bool forceParDirectionSwitch() const { return false; }
430 /// Does the inset force a specific encoding?
431 virtual Encoding const * forcedEncoding(Encoding const *, Encoding const *) const
435 /// Is the content of this inset part of the output document?
436 virtual bool producesOutput() const { return true; }
437 /// Is the content of this inset part of the immediate (visible) text sequence?
438 virtual bool isPartOfTextSequence() const { return producesOutput(); }
440 /// \return Tool tip for this inset.
441 /// This default implementation returns an empty string. This can be
442 /// either plain text or Qt html, and formatToolTip will be called
443 /// on it before display in both cases.
444 virtual docstring toolTip(BufferView const & bv, int x, int y) const;
446 /// \return Context menu identifier. This function determines
447 /// whose Inset's menu should be shown for the given position.
448 virtual std::string contextMenu(BufferView const & bv, int x, int y) const;
450 /// \return Context menu identifier for this inset.
451 /// This default implementation returns an empty string.
452 virtual std::string contextMenuName() const;
455 virtual docstring layoutName() const;
457 virtual InsetLayout const & getLayout() const;
459 virtual bool isPassThru() const { return getLayout().isPassThru(); }
460 /// Is this inset's layout defined in the document's textclass?
461 bool undefined() const;
462 /// should this inset be handled like a normal character?
463 /// (a character can be a letter or punctuation)
464 virtual bool isChar() const { return false; }
465 /// is this equivalent to a letter?
466 /// (a letter is a character that is considered part of a word)
467 virtual bool isLetter() const { return false; }
468 /// is this equivalent to a space (which is BTW different from
469 /// a line separator)?
470 virtual bool isSpace() const { return false; }
471 /// does this inset try to use all available space (like \\hfill does)?
472 virtual bool isHfill() const { return false; }
481 /// should we have a non-filled line before this inset?
482 virtual DisplayType display() const { return Inline; }
483 /// indentation before this inset (only needed for displayed hull insets with fleqn option)
484 virtual int indent(BufferView const &) const { return 0; }
486 virtual LyXAlignment contentAlignment() const { return LYX_ALIGN_NONE; }
487 /// should we break lines after this inset?
488 virtual bool isLineSeparator() const { return false; }
489 /// should paragraph indendation be omitted in any case?
490 virtual bool neverIndent() const { return false; }
491 /// dumps content to lyxerr
492 virtual void dump() const;
493 /// write inset in .lyx format
494 virtual void write(std::ostream &) const {}
495 /// read inset in .lyx format
496 virtual void read(Lexer &) {}
497 /** Export the inset to LaTeX.
498 * Don't use a temporary stringstream if the final output is
499 * supposed to go to a file.
500 * \sa Buffer::writeLaTeXSource for the reason.
502 virtual void latex(otexstream &, OutputParams const &) const {}
503 /// returns true to override begin and end inset in file
504 virtual bool directWrite() const;
506 virtual bool allowSpellCheck() const { return false; }
508 /// if this insets owns text cells (e.g. InsetText) return cell num
509 virtual Text * getText(int /*num*/) const { return 0; }
511 /** Adds a LaTeX snippet to the Preview Loader for transformation
512 * into a bitmap image. Does not start the laoding process.
514 * Most insets have no interest in this capability, so the method
517 virtual void addPreview(DocIterator const &,
518 graphics::PreviewLoader &) const {}
520 /** Classifies the unicode characters appearing in a math inset
521 * depending on whether they are to be translated as latex
522 * math/text commands or used as math symbols without translation.
524 * Only math insets have interest in this classification, so the
525 * method defaults to empty.
527 virtual void initUnicodeMath() const {}
529 /// Add an entry to the TocList
530 /// Pass a DocIterator that points at the paragraph containing
533 /// \param output_active : is the inset active or is it in an inactive
534 /// branch or a note?
536 /// \param utype : is the toc being generated for use by the output
539 /// \param tocbackend : where to add the toc information.
540 virtual void addToToc(DocIterator const & /* di */,
541 bool /* output_active */,
542 UpdateType /* utype*/,
543 TocBackend & /* tocbackend */) const {}
544 /// Collect BibTeX information
545 virtual void collectBibKeys(InsetIterator const &, support::FileNameList &) const {}
546 /// Update the counters of this inset and of its contents.
547 /// The boolean indicates whether we are preparing for output, e.g.,
549 virtual void updateBuffer(ParIterator const &, UpdateType) {}
551 /// Updates the inset's dialog
552 virtual Buffer const * updateFrontend() const;
555 /// returns LyX code associated with the inset. Used for TOC, ...)
556 virtual InsetCode lyxCode() const { return NO_CODE; }
559 enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
560 /// return text or mathmode if that is possible to determine
561 virtual mode_type currentMode() const { return UNDECIDED_MODE; }
562 /// returns whether changing mode during latex export is forbidden
563 virtual bool lockedMode() const { return false; }
564 /// returns whether only ascii chars are allowed during latex export
565 virtual bool asciiOnly() const { return false; }
566 /// returns whether this inset is allowed in other insets of given mode
567 virtual bool allowedIn(mode_type) const { return true; }
569 * The font is inherited from the parent for LaTeX export if this
570 * method returns true. No open font changes are closed in front of
571 * the inset for LaTeX export, and the font is inherited for all other
572 * exports as well as on screen.
573 * If this method returns false all open font changes are closed in
574 * front of the inset for LaTeX export. The default font is used
575 * inside the inset for all exports and on screen.
577 virtual bool inheritFont() const { return true; }
579 * If this method returns true all explicitly set font attributes
580 * are reset during editing operations.
581 * For copy/paste operations the language is never changed, since
582 * the language of a given text never changes if the text is
583 * formatted differently, while other font attribues like size may
584 * need to change if the text is copied from one environment to
586 * If this method returns false no font attribute is reset.
587 * The default implementation returns true if the resetFont layout
588 * tag is set and otherwise the negation of inheritFont(),
589 * since inherited inset font attributes do not need to be changed,
590 * and non-inherited ones need to be set explicitly.
592 virtual bool resetFontEdit() const;
594 /// set the change for the entire inset
595 virtual void setChange(Change const &) {}
596 /// accept the changes within the inset
597 virtual void acceptChanges() {}
598 /// reject the changes within the inset
599 virtual void rejectChanges() {}
602 virtual bool needsCProtection(bool const, bool const) const { return false; }
605 virtual ColorCode backgroundColor(PainterInfo const &) const;
607 virtual ColorCode labelColor() const;
609 enum { TEXT_TO_INSET_OFFSET = 4 };
611 /// Determine the action of backspace and delete: do we select instead of
612 /// deleting if not already selected?
613 virtual bool confirmDeletion() const { return false; }
617 Inset(Buffer * buf) : buffer_(buf) {}
618 Inset(Inset const &) : buffer_(0) {}
620 /// replicate ourselves
621 friend class InsetList;
622 friend class MathAtom;
623 virtual Inset * clone() const = 0;
625 /** The real dispatcher.
626 * Gets normally called from Cursor::dispatch(). Cursor::dispatch()
627 * assumes the common case of 'LFUN handled, need update'.
628 * This has to be overriden by calling Cursor::undispatched() or
629 * Cursor::noScreenUpdate() if appropriate.
630 * If you need to call the dispatch method of some inset directly
631 * you may have to explicitly request an update at that place. Don't
632 * do it in doDispatch(), since that causes nested updates when
633 * called from Cursor::dispatch(), and these can lead to crashes.
636 virtual void doDispatch(Cursor & cur, FuncRequest & cmd);