4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
13 First some explanation about what a Cursor really is, from local to
16 * a CursorSlice indicates the position of the cursor at local level.
17 It contains in particular:
18 * idx(): the cell that contains the cursor (for Tabular or math
19 arrays). Always 0 for 'plain' insets
20 * pit(): the index of the current paragraph (only for text)
21 * pos(): the position in the current paragraph (or in the math
23 * inset(): the inset in which the cursor is. For a InsetTabular,
24 this is the tabular itself, not the cell inset (which is an
27 * a DocIterator indicated the position of the cursor in the document.
28 It knows about the current buffer (buffer() method) and contains a
29 vector of CursorSlices that describes the nesting of insets up to the
30 point of interest. Note that operator<< has been implemented, so that
31 one can send a DocIterator to a stream to see its value. Try it, it is
32 very helpful to understand the cursor layout.
33 * when using idx/pit/pos on a DocIterator, one gets the information
34 from the inner slice (this slice can be accessed as top())
35 * inMathed() returns true when the cursor is in a math formula
36 * inTexted() returns true when the cursor is in text
37 * innerTextSlice() returns the deepest slice that is text (useful
38 when one is in a math equation and looks for the enclosing text)
40 * A CursorData is a descendant of Dociterator that contains
41 * a second DocIterator object, the anchor, that is useful when
43 * some other data that describes current selection, cursor font, etc.
45 This class is mostly used only for undo and contains the Cursor
46 elements that are not GUI-related. In LyX 2.0, Cursor was directly
47 deriving from DocIterator
49 * A Cursor is a descendant of CursorData that contains interesting
50 display-related information, in particular the BufferView that owns it.
56 #include "DispatchResult.h"
57 #include "DocIterator.h"
61 #include "mathed/MathParser_flags.h"
73 class InsetMathUnknown;
76 * This class describes the position of a cursor within a document,
77 * but does not contain any detail about the view. It is currently
78 * only used to save cursor position in Undo, but culd be extended to
79 * handle the methods that only need this data.
81 class CursorData : public DocIterator
87 explicit CursorData(Buffer * buffer);
89 explicit CursorData(DocIterator const & dit);
91 friend std::ostream & operator<<(std::ostream & os, CursorData const & cur);
92 friend LyXErr & operator<<(LyXErr & os, CursorData const & cur);
94 /// reset cursor bottom to the beginning of the top inset
95 // (sort of 'chroot' environment...)
98 /// this (intentionally) does neither touch anchor nor selection status
99 void setCursor(DocIterator const & it);
100 /// set the cursor to dit normalised against the anchor, and set selection.
101 void setCursorSelectionTo(DocIterator dit);
102 /// sets the cursor to the normalized selection anchor
103 void setCursorToAnchor();
108 /// selection active?
109 bool selection() const { return selection_; }
110 /// set selection; this is lower level than (set|clear)Selection
111 void selection(bool sel) { selection_ = sel; }
112 /// do we have a multicell selection?
113 bool selIsMultiCell() const
114 { return selection_ && selBegin().idx() != selEnd().idx(); }
115 /// do we have a multiline selection?
116 bool selIsMultiLine() const
117 { return selection_ && selBegin().pit() != selEnd().pit(); }
119 void setWordSelection(bool set) { word_selection_ = set; }
121 bool wordSelection() { return word_selection_; }
122 /// did we place the anchor?
123 bool mark() const { return mark_; }
124 /// did we place the anchor?
125 void setMark(bool mark) { mark_ = mark; }
128 /// set selection at given position
129 void setSelection(DocIterator const & where, int n);
131 void clearSelection();
132 /// check whether selection contains specific type of inset
133 /// returns 0 if no selection was made
134 bool insetInSelection(InsetCode const & inset);
135 /// count occurences of specific inset type in the selection
136 /// returns 0 if no selection was made
137 int countInsetsInSelection(InsetCode const & inset);
139 /// access to normalized selection anchor
140 CursorSlice normalAnchor() const;
141 /// access to real selection anchor
142 DocIterator const & realAnchor() const { return anchor_; }
143 DocIterator & realAnchor() { return anchor_; }
144 /// sets anchor to cursor position
147 /// access start of selection
148 CursorSlice selBegin() const;
149 /// access end of selection
150 CursorSlice selEnd() const;
151 /// access start of selection
152 DocIterator selectionBegin() const;
153 /// access end of selection
154 DocIterator selectionEnd() const;
157 docstring selectionAsString(bool with_label) const;
158 /// get some interesting description of top position
159 void info(odocstream & os, bool devel_mode) const;
161 docstring currentState(bool devel_mode) const;
163 /// auto-correct mode
164 bool autocorrect() const { return autocorrect_; }
165 /// auto-correct mode
166 bool & autocorrect() { return autocorrect_; }
168 /// fix cursor in circumstances that should never happen.
169 /// \retval true if a fix occurred.
171 /// Repopulate the slices insets from bottom to top. Useful
172 /// for stable iterators or Undo data.
180 /// makes sure the next operation will be stored
181 void finishUndo() const;
182 /// open a new group of undo operations. Groups can be nested.
183 void beginUndoGroup() const;
184 /// end the current undo group
185 void endUndoGroup() const;
187 /// The general case: prepare undo for an arbitrary range.
188 void recordUndo(pit_type from, pit_type to) const;
189 /// Convenience: prepare undo for the range between 'from' and cursor.
190 void recordUndo(pit_type from) const;
191 /// Convenience: prepare undo for the single paragraph or cell
192 /// containing the cursor
193 void recordUndo(UndoKind kind = ATOMIC_UNDO) const;
194 /// Convenience: prepare undo for the inset containing the cursor
195 void recordUndoInset(Inset const * inset = 0) const;
196 /// Convenience: prepare undo for the whole buffer
197 void recordUndoFullBuffer() const;
198 /// Convenience: prepare undo for buffer parameters
199 void recordUndoBufferParams() const;
200 /// Convenience: prepare undo for the selected paragraphs or cells
201 void recordUndoSelection() const;
203 /// hook for text input to maintain the "new born word"
204 void markNewWordPosition();
205 /// The position of the new born word
206 /// As the user is entering a word without leaving it
207 /// the result is not empty. When not in text mode
208 /// and after leaving the word the result is empty.
209 DocIterator newWord() const { return new_word_; }
211 /// are we in math mode (2), text mode (1) or unsure (0)?
214 /// Return true if the next or previous inset has confirmDeletion depending
215 /// on the boolean before. If there is a selection, return true if at least
216 /// one inset in the selection has confirmDeletion.
217 bool confirmDeletion(bool before = false) const;
220 /// validate the "new born word" position
221 void checkNewWordPosition();
222 /// clear the "new born word" position
223 void clearNewWordPosition();
225 /// the anchor position
227 /// do we have a selection?
229 /// are we on the way to get one?
231 /// are we in word-selection mode? This is set when double clicking.
232 bool word_selection_;
234 /// the start of the new born word
235 DocIterator new_word_;
237 // math specific stuff that could be promoted to "global" later
239 /// do we allow autocorrection
242 // FIXME: make them private
244 /// The current font settings. This holds the settings for output.
246 /// The current display font. This holds the settings of the text
248 Font real_current_font;
252 /// The cursor class describes the position of a cursor within a document.
253 class Cursor : public CursorData
256 /// create the cursor of a BufferView
257 explicit Cursor(BufferView & bv);
259 /// add a new cursor slice
260 void push(Inset & inset);
261 /// add a new cursor slice, place cursor at front (move backwards)
262 void pushBackward(Inset & inset);
263 /// try to put cursor in inset before it in entry cell, or next one
264 /// if it is not empty, or exit the slice if there is no next one.
265 void editInsertedInset();
267 /// pop one level off the cursor
269 /// pop one slice off the cursor stack and go backwards
271 /// pop one slice off the cursor stack and go forward
273 /// set the cursor data
274 void setCursorData(CursorData const & data);
276 /// returns true if we made a decision
277 bool getStatus(FuncRequest const & cmd, FuncStatus & flag) const;
278 /// dispatch from innermost inset upwards
279 void dispatch(FuncRequest const & cmd);
280 /// display a message
281 void message(docstring const & msg) const;
282 /// display an error message
283 void errorMessage(docstring const & msg) const;
284 /// get the resut of the last dispatch
285 DispatchResult const & result() const;
288 void setCurrentFont();
291 * Update the selection status and save permanent
292 * selection if needed.
293 * @param selecting the new selection status
294 * @return whether the selection status has changed
296 bool selHandle(bool selecting);
298 /// returns x,y position
299 void getPos(int & x, int & y) const;
300 /// return logical positions between which the cursor is situated
302 * If the cursor is at the edge of a row, the position which is "over the
303 * edge" will be returned as -1.
305 void getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const;
306 /// the row in the paragraph we're in
307 Row const & textRow() const;
312 /// move visually one step to the right
314 * @note: This method may move into an inset unless skip_inset == true.
315 * @note: This method may move into a new paragraph.
316 * @note: This method may move out of the current slice.
317 * @return: true if moved, false if not moved
319 bool posVisRight(bool skip_inset = false);
320 /// move visually one step to the left
322 * @note: This method may move into an inset unless skip_inset == true.
323 * @note: This method may move into a new paragraph.
324 * @note: This method may move out of the current slice.
325 * @return: true if moved, false if not moved
327 bool posVisLeft(bool skip_inset = false);
328 /// move visually to next/previous row
330 * Assuming we were to keep moving left (right) from the current cursor
331 * position, place the cursor at the rightmost (leftmost) edge of the
332 * new row to which we would move according to visual-mode cursor movement.
333 * This could be either the next or the previous row, depending on the
334 * direction in which we're moving, and whether we're in an LTR or RTL
336 * @note: The new position may even be in a new paragraph.
337 * @note: This method will not move out of the current slice.
338 * @return: false if not moved (no more rows to move to in given direction)
339 * @return: true if moved
341 bool posVisToNewRow(bool movingLeft);
342 /// move to right or left extremity of the current row
343 void posVisToRowExtremity(bool left);
344 /// Should interpretation of the arrow keys be reversed?
345 bool reverseDirectionNeeded() const;
348 /// Insertion (mathed and texted)
350 /// insert a single char
351 void insert(char_type c);
353 void insert(docstring const & str);
355 void insert(Inset *);
357 /// Insertion (mathed only)
359 /// insert a math atom
360 void insert(MathAtom const &);
361 /// insert a string of atoms
362 void insert(MathData const &);
363 /// Like insert, but moves the selection inside the inset if possible
364 void niceInsert(MathAtom const & at);
365 /// return the number of inserted array items
366 /// FIXME: document properly
367 int niceInsert(docstring const & str, Parse::flags f = Parse::NORMAL,
370 /// FIXME: rename to something sensible showing difference to x_target()
371 /// in pixels from left of screen, set to current position if unset
373 /// set the targetX to x
374 void setTargetX(int x);
375 /// return targetX or -1 if unset
376 int x_target() const;
377 /// set targetX to current position
379 /// clear targetX, i.e. set it to -1
381 /// set offset to actual position - targetX
382 void updateTextTargetOffset();
383 /// distance between actual and targeted position during last up/down in text
384 int textTargetOffset() const;
386 /// access to owning BufferView
387 BufferView & bv() const;
388 /// reset cursor bottom to the beginning of the top inset
389 // (sort of 'chroot' environment...)
393 * the event was not (yet) dispatched.
395 * Should only be called by an inset's doDispatch() method. It means:
396 * I, the doDispatch() method of InsetFoo, hereby declare that I am
397 * not able to handle that request and trust my parent will do the
398 * Right Thing (even if my getStatus partner said that I can do it).
399 * It is sort of a kludge that should be used only rarely...
401 void undispatched() const;
402 /// the event was already dispatched
403 void dispatched() const;
405 /// Describe the screen update that should be done
406 void screenUpdateFlags(Update::flags f) const;
408 * Reset update flags to Update::None.
410 * Should only be called by an inset's doDispatch() method. It means:
411 * I handled that request and I can reassure you that the screen does
412 * not need to be re-drawn and all entries in the coord cache stay
413 * valid (and there are no other things to put in the coord cache).
414 * This is a fairly rare event as well and only some optimization.
415 * Not using noScreenUpdate() should never be wrong.
417 void noScreenUpdate() const;
419 /// Forces an updateBuffer() call
420 void forceBufferUpdate() const;
421 /// Removes any pending updateBuffer() call
422 void clearBufferUpdate() const;
423 /// Do we need to call updateBuffer()?
424 bool needBufferUpdate() const;
426 /// Repopulate the slices insets from bottom to top. Useful
427 /// for stable iterators or Undo data.
431 void checkBufferStructure();
433 /// Determine if x falls to the left or to the side of the middle of the
434 /// inset, and advance the cursor to match this position. If edit is true,
435 /// keep the cursor in front of the inset if it matter for dialogs.
436 /// Note: it does not handle RTL text yet, and is only used in math for now.
437 void moveToClosestEdge(int x, bool edit = false);
439 /// whether the cursor is either at the first or last row
440 bool atFirstOrLastRow(bool up);
446 DocIterator const & beforeDispatchCursor() const { return beforeDispatchCursor_; }
448 void saveBeforeDispatchPosXY();
454 mutable DispatchResult disp_;
456 * The target x position of the cursor. This is used for when
457 * we have text like :
459 * blah blah blah blah| blah blah blah
461 * blah blah blah blah blah blah
463 * When we move onto row 3, we would like to be vertically aligned
464 * with where we were in row 1, despite the fact that row 2 is
468 /// if a x_target cannot be hit exactly in a text, put the difference here
469 int textTargetOffset_;
470 /// position before dispatch started
471 DocIterator beforeDispatchCursor_;
472 /// cursor screen coordinates before dispatch started
473 int beforeDispatchPosX_;
474 int beforeDispatchPosY_;
476 ///////////////////////////////////////////////////////////////////
478 // The part below is the non-integrated rest of the original math
479 // cursor. This should be either generalized for texted or moved
480 // back to the math insets.
482 ///////////////////////////////////////////////////////////////////
485 /// return false for empty math insets
486 /// Use force to skip the confirmDeletion check.
487 bool erase(bool force = false);
488 bool backspace(bool force = false);
490 /// move the cursor up by sending an internal LFUN_UP
491 /// return true if fullscreen update is needed
493 /// move the cursor up by sending an internal LFUN_DOWN,
494 /// return true if fullscreen update is needed
496 /// move up/down in a text inset, called for LFUN_UP/DOWN,
497 /// return true if successful, updateNeeded set to true if fullscreen
498 /// update is needed, otherwise it's not touched
499 bool upDownInText(bool up, bool & updateNeeded);
500 /// move up/down in math or any non text inset, call for LFUN_UP/DOWN
501 /// return true if successful
502 bool upDownInMath(bool up);
503 /// move forward in math. word: whether to skip a whole "word" (insets with
504 /// the same mathclass)
505 bool mathForward(bool word);
507 bool mathBackward(bool word);
511 void plainInsert(MathAtom const & at);
513 /// interpret name of a macro or ditch it if \c cancel is true.
514 /// Returns true if something got inserted.
515 bool macroModeClose(bool cancel = false);
516 /// are we currently typing the name of a macro?
517 bool inMacroMode() const;
518 /// get access to the macro we are currently typing
519 InsetMathUnknown * activeMacro();
520 /// get access to the macro we are currently typing
521 InsetMathUnknown const * activeMacro() const;
522 /// the name of the macro we are currently inputting
523 docstring macroName();
525 /// replace selected stuff with at, placing the former
526 // selection in entry cell of atom
527 void handleNest(MathAtom const & at);
529 /// make sure cursor position is valid
530 /// FIXME: It does a subset of fixIfBroken. Maybe merge them?
533 /// injects content of a cell into parent
535 /// split font inset etc
536 void handleFont(std::string const & font);
538 /// can we enter the inset?
539 bool openable(MathAtom const &) const;
540 /// font at cursor position
541 Font getFont() const;
546 * Notifies all insets which appear in \c old, but not in \c cur. And then
547 * notify all insets which appear in \c cur, but not in \c old.
548 * \returns true if cursor is now invalid, e.g. if some insets in
549 * higher cursor slices of \c old do not exist anymore. In this case
550 * it may be necessary to use Use Cursor::fixIfBroken.
552 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur);