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