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