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