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