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