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