]> git.lyx.org Git - lyx.git/blob - src/Cursor.h
Avoid full metrics computation with Update:FitCursor
[lyx.git] / src / Cursor.h
1 // -*- C++ -*-
2 /**
3  * \file Cursor.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author André Pönitz
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 /*
13 First some explanation about what a Cursor really is, from local to
14 global.
15
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
22            equation in mathed).
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
25     InsetTableCell).
26
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)
39
40 * A CursorData is a descendant of Dociterator that contains
41   * a second DocIterator object, the anchor, that is useful when
42     selecting.
43   * some other data that describes current selection, cursor font, etc.
44
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
48
49 * A Cursor is a descendant of CursorData that contains interesting
50   display-related information, in particular the BufferView that owns it.
51 */
52
53 #ifndef LCURSOR_H
54 #define LCURSOR_H
55
56 #include "DispatchResult.h"
57 #include "DocIterator.h"
58 #include "Font.h"
59 #include "Undo.h"
60
61 #include "mathed/MathParser_flags.h"
62
63
64 namespace lyx {
65
66 class Buffer;
67 class BufferView;
68 class FuncStatus;
69 class FuncRequest;
70 class Row;
71
72 // these should go
73 class InsetMathUnknown;
74
75 /**
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.
80  **/
81 class CursorData : public DocIterator
82 {
83 public:
84         ///
85         CursorData();
86         ///
87         explicit CursorData(Buffer * buffer);
88         ///
89         explicit CursorData(DocIterator const & dit);
90         /// output
91         friend std::ostream & operator<<(std::ostream & os, CursorData const & cur);
92         friend LyXErr & operator<<(LyXErr & os, CursorData const & cur);
93
94         /// reset cursor bottom to the beginning of the top inset
95         // (sort of 'chroot' environment...)
96         void reset();
97         /// sets cursor part
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();
104
105         //
106         // selection
107         //
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(); }
118         ///
119         void setWordSelection(bool set) { word_selection_ = set; }
120         ///
121         bool wordSelection() const { 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; }
126         ///
127         void setSelection();
128         /// set selection at given position
129         void setSelection(DocIterator const & where, int n);
130         ///
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) const;
135         /// count occurences of specific inset type in the selection
136         /// returns 0 if no selection was made
137         int countInsetsInSelection(InsetCode const & inset) const;
138
139         /// access to normalized selection anchor
140         // FIXME: this should return a full DocIterator
141         CursorSlice normalAnchor() const;
142         /// access to real selection anchor
143         DocIterator const & realAnchor() const { return anchor_; }
144         DocIterator & realAnchor() { return anchor_; }
145         /// sets anchor to cursor position
146         void resetAnchor();
147
148         /// access start of selection
149         CursorSlice selBegin() const;
150         /// access end of selection
151         CursorSlice selEnd() const;
152         /// access start of selection
153         DocIterator selectionBegin() const;
154         /// access end of selection
155         DocIterator selectionEnd() const;
156
157         ///
158         docstring selectionAsString(bool const with_label,
159                                     bool const skipdelete = false) const;
160         /// get some interesting description of top position
161         void info(odocstream & os, bool devel_mode) const;
162         ///
163         docstring currentState(bool devel_mode) const;
164
165         /// fix cursor in circumstances that should never happen.
166         /// \retval true if a fix occurred.
167         bool fixIfBroken();
168         /// Repopulate the slices insets from bottom to top. Useful
169         /// for stable iterators or Undo data.
170         void sanitize();
171
172         ///
173         bool undoAction();
174         ///
175         bool redoAction();
176
177         /// makes sure the next operation will be stored
178         void finishUndo() const;
179         /// open a new group of undo operations. Groups can be nested.
180         void beginUndoGroup() const;
181         /// end the current undo group
182         void endUndoGroup() const;
183         /// end abruptly the current group and create a new one wih the same nesting level
184         void splitUndoGroup() const;
185
186         /// The general case: prepare undo for an arbitrary range.
187         void recordUndo(pit_type from, pit_type to) const;
188         /// Convenience: prepare undo for the range between 'from' and cursor.
189         void recordUndo(pit_type from) const;
190         /// Convenience: prepare undo for the single paragraph or cell
191         /// containing the cursor
192         void recordUndo(UndoKind kind = ATOMIC_UNDO) const;
193         /// Convenience: prepare undo for the inset containing the cursor
194         void recordUndoInset(Inset const * inset = nullptr) const;
195         /// Convenience: prepare undo for the whole buffer
196         void recordUndoFullBuffer() const;
197         /// Convenience: prepare undo for buffer parameters
198         void recordUndoBufferParams() const;
199         /// Convenience: prepare undo for the selected paragraphs or cells
200         void recordUndoSelection() const;
201
202         /// hook for text input to maintain the "new born word"
203         void markNewWordPosition();
204         /// The position of the new born word
205         /// As the user is entering a word without leaving it
206         /// the result is not empty. When not in text mode
207         /// and after leaving the word the result is empty.
208         DocIterator newWord() const { return new_word_; }
209
210         /// are we in math mode (2), text mode (1) or unsure (0)?
211         int currentMode() const;
212
213         /// Return true if the next or previous inset has confirmDeletion depending
214         /// on the boolean before. If there is a selection, return true if at least
215         /// one inset in the selection has confirmDeletion.
216         bool confirmDeletion(bool before = false) const;
217
218 private:
219         /// validate the "new born word" position
220         void checkNewWordPosition();
221         /// clear the "new born word" position
222         void clearNewWordPosition();
223
224         /// the anchor position
225         DocIterator anchor_;
226         /// do we have a selection?
227         bool selection_;
228         /// are we on the way to get one?
229         bool mark_;
230         /// are we in word-selection mode? This is set when double clicking.
231         bool word_selection_;
232
233         /// the start of the new born word
234         DocIterator new_word_;
235         //
236         // math specific stuff that could be promoted to "global" later
237         //
238
239         // FIXME: make them private
240 public:
241         /// The current font settings. This holds the settings for output.
242         Font current_font;
243         /// The current display font. This holds the settings of the text
244         /// in the workarea.
245         Font real_current_font;
246 };
247
248
249 /// The cursor class describes the position of a cursor within a document.
250 class Cursor : public CursorData
251 {
252 public:
253         /// create the cursor of a BufferView
254         explicit Cursor(BufferView & bv);
255
256         /// add a new cursor slice
257         void push(Inset & inset);
258         /// add a new cursor slice, place cursor at front (move backwards)
259         void pushBackward(Inset & inset);
260         /// try to put cursor in inset before it in entry cell, or next one
261         /// if it is not empty, or exit the slice if there is no next one.
262         void editInsertedInset();
263
264         /// pop one level off the cursor
265         void pop();
266         /// pop one slice off the cursor stack and go backwards
267         bool popBackward();
268         /// pop one slice off the cursor stack and go forward
269         bool popForward();
270         /// set the cursor data
271         void setCursorData(CursorData const & data);
272
273         /// returns true if we made a decision
274         bool getStatus(FuncRequest const & cmd, FuncStatus & status) const;
275         /// dispatch from innermost inset upwards
276         void dispatch(FuncRequest const & cmd);
277         /// display a message
278         void message(docstring const & msg) const;
279         /// display an error message
280         void errorMessage(docstring const & msg) const;
281         /// get the result of the last dispatch
282         DispatchResult const & result() const;
283
284         /// Set the cursor language from current input method language
285         /* Considers first exact math with the codes used in the document,
286          * then approximate match among the same list, and finally exact
287          * or partial match with the whole list of languages.
288          */
289         void setLanguageFromInput();
290         /// Set the current font of the cursor from its location.
291         void setCurrentFont();
292
293         /**
294          * Update the selection status and save permanent
295          * selection if needed.
296          * @param selecting the new selection status
297          * @return whether the selection status has changed
298          */
299         bool selHandle(bool selecting);
300
301         /// returns x,y position
302         void getPos(int & x, int & y) const;
303         /// return logical positions between which the cursor is situated
304         /**
305          * If the cursor is at the edge of a row, the position which is "over the
306          * edge" will be returned as -1.
307          */
308         void getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const;
309         /// the row in the paragraph we're in
310         Row const & textRow() const;
311
312         //
313         // common part
314         //
315         /// move visually one step to the right
316         /**
317          * @note: This method may move into an inset unless skip_inset == true.
318          * @note: This method may move into a new paragraph.
319          * @note: This method may move out of the current slice.
320          * @return: true if moved, false if not moved
321          */
322         bool posVisRight(bool skip_inset = false);
323         /// move visually one step to the left
324         /**
325          * @note: This method may move into an inset unless skip_inset == true.
326          * @note: This method may move into a new paragraph.
327          * @note: This method may move out of the current slice.
328          * @return: true if moved, false if not moved
329          */
330         bool posVisLeft(bool skip_inset = false);
331         /// move visually to next/previous row
332         /**
333          * Assuming we were to keep moving left (right) from the current cursor
334          * position, place the cursor at the rightmost (leftmost) edge of the
335          * new row to which we would move according to visual-mode cursor movement.
336          * This could be either the next or the previous row, depending on the
337          * direction in which we're moving, and whether we're in an LTR or RTL
338          * paragraph.
339          * @note: The new position may even be in a new paragraph.
340          * @note: This method will not move out of the current slice.
341          * @return: false if not moved (no more rows to move to in given direction)
342          * @return: true if moved
343          */
344         bool posVisToNewRow(bool movingLeft);
345         /// move to right or left extremity of the current row
346         void posVisToRowExtremity(bool left);
347         /// Should interpretation of the arrow keys be reversed?
348         bool reverseDirectionNeeded() const;
349
350         ///
351         ///  Insertion (mathed and texted)
352         ///
353         /// insert a single char
354         void insert(char_type c);
355         /// insert a string
356         void insert(docstring const & str);
357         /// insert an inset
358         void insert(Inset *);
359         ///
360         ///  Insertion (mathed only)
361         ///
362         /// insert a math atom
363         void insert(MathAtom const &);
364         /// insert a string of atoms
365         void insert(MathData const &);
366         /// Like insert, but moves the selection inside the inset if possible
367         void niceInsert(MathAtom const & at);
368         /// return the number of inserted array items
369         /// FIXME: document properly
370         int niceInsert(docstring const & str, Parse::flags f = Parse::NORMAL,
371                         bool enter = true);
372
373         /// FIXME: rename to something sensible showing difference to x_target()
374         /// in pixels from left of screen, set to current position if unset
375         int targetX() const;
376         /// set the targetX to x
377         void setTargetX(int x);
378         /// return targetX or -1 if unset
379         int x_target() const;
380         /// set targetX to current position
381         void setTargetX();
382         /// clear targetX, i.e. set it to -1
383         void clearTargetX();
384         /// return x position of latest mouse press or -1 if unset
385         int xClickPos() const { return x_clickpos_; }
386         /// return y position of latest mouse press or -1 if unset
387         int yClickPos() const { return y_clickpos_; }
388         /// register mouse press coordinates
389         void setClickPos(int x, int y);
390         /// set offset to actual position - targetX
391         void updateTextTargetOffset();
392         /// distance between actual and targeted position during last up/down in text
393         int textTargetOffset() const;
394
395         /// access to owning BufferView
396         BufferView & bv() const;
397         /// reset cursor bottom to the beginning of the top inset
398         // (sort of 'chroot' environment...)
399         void reset();
400
401         /**
402          * the event was not (yet) dispatched.
403          *
404          * Should only be called by an inset's doDispatch() method. It means:
405          * I, the doDispatch() method of InsetFoo, hereby declare that I am
406          * not able to handle that request and trust my parent will do the
407          * Right Thing (even if my getStatus partner said that I can do it).
408          * It is sort of a kludge that should be used only rarely...
409          */
410         void undispatched() const;
411         /// the event was already dispatched
412         void dispatched() const;
413
414         /// Describe the screen update that should be done
415         void screenUpdateFlags(Update::flags f) const;
416         /**
417          * Reset update flags to Update::None.
418          *
419          * Should only be called by an inset's doDispatch() method. It means:
420          * I handled that request and I can reassure you that the screen does
421          * not need to be re-drawn and all entries in the coord cache stay
422          * valid (and there are no other things to put in the coord cache).
423          * This is a fairly rare event as well and only some optimization.
424          * Not using noScreenUpdate() should never be wrong.
425          */
426         void noScreenUpdate() const;
427
428         /// Forces an updateBuffer() call
429         void forceBufferUpdate() const;
430         /// Removes any pending updateBuffer() call
431         void clearBufferUpdate() const;
432         /// Do we need to call updateBuffer()?
433         bool needBufferUpdate() const;
434
435         /// Repopulate the slices insets from bottom to top. Useful
436         /// for stable iterators or Undo data.
437         void sanitize();
438
439         ///
440         void checkBufferStructure();
441
442         /// Determine if x falls to the left or to the side of the middle of the
443         /// inset, and advance the cursor to match this position. If edit is true,
444         /// keep the cursor in front of the inset if it matter for dialogs.
445         /// Note: it does not handle RTL text yet, and is only used in math for now.
446         void moveToClosestEdge(int x, bool edit = false);
447
448         /// whether the cursor is either at the first or last row
449         bool atFirstOrLastRow(bool up);
450
451 public:
452 //private:
453
454         ///
455         DocIterator const & beforeDispatchCursor() const { return beforeDispatchCursor_; }
456         ///
457         void saveBeforeDispatchPosXY();
458
459 private:
460         ///
461         BufferView * bv_;
462         ///
463         mutable DispatchResult disp_;
464         /**
465          * The target x position of the cursor. This is used for when
466          * we have text like :
467          *
468          * blah blah blah blah| blah blah blah
469          * blah blah blah
470          * blah blah blah blah blah blah
471          *
472          * When we move onto row 3, we would like to be vertically aligned
473          * with where we were in row 1, despite the fact that row 2 is
474          * shorter than x()
475          */
476         int x_target_;
477         /// if a x_target cannot be hit exactly in a text, put the difference here
478         int textTargetOffset_;
479         /// Exact position of mouse click
480         int x_clickpos_;
481         int y_clickpos_;
482         /// position before dispatch started
483         DocIterator beforeDispatchCursor_;
484         /// cursor screen coordinates before dispatch started
485         int beforeDispatchPosX_;
486         int beforeDispatchPosY_;
487
488 ///////////////////////////////////////////////////////////////////
489 //
490 // The part below is the non-integrated rest of the original math
491 // cursor. This should be either generalized for texted or moved
492 // back to the math insets.
493 //
494 ///////////////////////////////////////////////////////////////////
495
496 public:
497         /// return false for empty math insets
498         /// Use force to skip the confirmDeletion check.
499         bool erase(bool force = false);
500         bool backspace(bool force = false);
501
502         /// move the cursor up by sending an internal LFUN_UP
503         /// return true if fullscreen update is needed
504         bool up();
505         /// move the cursor up by sending an internal LFUN_DOWN,
506         /// return true if fullscreen update is needed
507         bool down();
508         /// move up/down in a text inset, called for LFUN_UP/DOWN,
509         /// return true if successful, updateNeeded set to true if fullscreen
510         /// update is needed, otherwise it's not touched
511         bool upDownInText(bool up, bool & updateNeeded);
512         /// move up/down in math or any non text inset, call for LFUN_UP/DOWN
513         /// return true if successful
514         bool upDownInMath(bool up);
515         /// move forward in math. word: whether to skip a whole "word" (insets with
516         /// the same mathclass)
517         bool mathForward(bool word);
518         ///
519         bool mathBackward(bool word);
520         ///
521         void plainErase();
522         ///
523         void plainInsert(MathAtom const & at);
524
525         /// interpret name of a macro or ditch it if \c cancel is true.
526         /// Returns true if something got inserted.
527         bool macroModeClose(bool cancel = false);
528         /// are we currently typing the name of a macro?
529         bool inMacroMode() const;
530         /// get access to the macro we are currently typing
531         InsetMathUnknown * activeMacro();
532         /// get access to the macro we are currently typing
533         InsetMathUnknown const * activeMacro() const;
534         /// the name of the macro we are currently inputting
535         docstring macroName();
536
537         /// replace selected stuff with at, placing the former
538         // selection in entry cell of atom
539         void handleNest(MathAtom const & at);
540
541         /// make sure cursor position is valid
542         /// FIXME: It does a subset of fixIfBroken. Maybe merge them?
543         void normalize();
544
545         /// injects content of a cell into parent
546         void pullArg();
547         /// split font inset etc
548         void handleFont(std::string const & font);
549
550         /// can we enter the inset?
551         bool openable(MathAtom const &) const;
552         /// font at cursor position
553         Font getFont() const;
554 };
555
556
557 /**
558  * Notifies all insets which appear in \c old, but not in \c cur. And then
559  * notify all insets which appear in \c cur, but not in \c old.
560  * \returns true if cursor is now invalid, e.g. if some insets in
561  *   higher cursor slices of \c old do not exist anymore. In this case
562  *   it may be necessary to use Use Cursor::fixIfBroken.
563  */
564 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur);
565
566
567 } // namespace lyx
568
569 #endif // LCURSOR_H