]> git.lyx.org Git - lyx.git/blob - src/Cursor.h
4ca5f3108d928f66e88a0c43520334b26172c243
[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. I try to go from
14 more local to general.
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 Texted)
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.
24
25 * a DocIterator indicated the position of the cursor in the document.
26   It knows about the current buffer (buffer() method) and contains a
27   vector of CursorSlices that describes the nesting of insets up to the
28   point of interest. Note that operator<< has been implemented, so that
29   one can send a DocIterator to a stream to see its value. Try it, it is
30   very helpful to understand the cursor layout.
31   * when using idx/pit/pos on a DocIterator, one gets the information
32     from the inner slice (this slice can be accessed as top())
33   * inMathed() returns true when the cursor is in a math formula
34   * inTexted() returns true when the cursor is in text
35   * innerTextSlice() returns the deepest slice that is text (useful
36     when one is in a math equation and looks for the enclosing text)
37
38 * A CursorData is a descendent of Dociterator that contains
39   * a second DocIterator object, the anchor, that is useful when
40     selecting.
41   * some other data not interesting here
42 This class is used only for undo and contains the Cursor element that
43 are not GUI-related. In LyX 2.0, Cursor was directly deriving from
44 DocIterator
45
46 * A Cursor is a descendant of CursorData that contains interesting
47   display-related information, in particular targetX(), the horizontal
48   position of the cursor in pixels.
49   * one interesting method for what you want to do is textRow(), that
50     returns the inner Row object that contains the cursor
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 class Encoding;
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         ///
99         mutable DispatchResult disp_;
100         /// do we have a selection?
101         bool selection_;
102         /// are we on the way to get one?
103         bool mark_;
104         /// are we in word-selection mode? This is set when double clicking.
105         bool word_selection_;
106         /// If true, we are behind the previous char, otherwise we are in front
107         // of the next char. This only make a difference when we are in front
108         // of a big inset spanning a whole row and computing coordinates for
109         // displaying the cursor.
110         bool logicalpos_;
111
112 // FIXME: make them protected.
113 public:
114         /// the current font settings
115         Font current_font;
116         /// the current font
117         Font real_current_font;
118
119 protected:
120
121         //
122         // math specific stuff that could be promoted to "global" later
123         //
124         /// do we allow autocorrection
125         bool autocorrect_;
126         /// are we entering a macro name?
127         bool macromode_;
128 };
129
130
131 /// The cursor class describes the position of a cursor within a document.
132 class Cursor : public CursorData
133 {
134 public:
135         /// create the cursor of a BufferView
136         explicit Cursor(BufferView & bv);
137
138         /// returns true if we made a decision
139         bool getStatus(FuncRequest const & cmd, FuncStatus & flag) const;
140         /// dispatch from innermost inset upwards
141         void dispatch(FuncRequest const & cmd);
142         /// get the resut of the last dispatch
143         DispatchResult const & result() const;
144         /// add a new cursor slice
145         void push(Inset & inset);
146         /// add a new cursor slice, place cursor at front (move backwards)
147         void pushBackward(Inset & inset);
148         /// pop one level off the cursor
149         void pop();
150         /// pop one slice off the cursor stack and go backwards
151         bool popBackward();
152         /// pop one slice off the cursor stack and go forward
153         bool popForward();
154         /// make sure we are outside of given inset
155         void leaveInset(Inset const & inset);
156         /// set the cursor data
157         void setCursorData(CursorData const & data);
158         /// sets cursor part
159         void setCursor(DocIterator const & it);
160         /// sets the cursor to the normalized selection anchor
161         void setCursorToAnchor();
162
163         ///
164         void setCurrentFont();
165
166         //
167         // selection
168         //
169         /// selection active?
170         bool selection() const { return selection_; }
171         /// set selection;
172         void setSelection(bool sel) { selection_ = sel; }
173         /// do we have a multicell selection?
174         bool selIsMultiCell() const 
175                 { return selection_ && selBegin().idx() != selEnd().idx(); }
176         /// do we have a multiline selection?
177         bool selIsMultiLine() const 
178                 { return selection_ && selBegin().pit() != selEnd().pit(); }
179         /// 
180         void setWordSelection(bool set) { word_selection_ = set; }
181         ///
182         bool wordSelection() { return word_selection_; }
183         /// did we place the anchor?
184         bool mark() const { return mark_; }
185         /// did we place the anchor?
186         void setMark(bool mark) { mark_ = mark; }
187         ///
188         void setSelection();
189         /// set selection at given position
190         void setSelection(DocIterator const & where, int n);
191         ///
192         void clearSelection();
193         /// access start of selection
194         CursorSlice selBegin() const;
195         /// access end of selection
196         CursorSlice selEnd() const;
197         /// access start of selection
198         DocIterator selectionBegin() const;
199         /// access end of selection
200         DocIterator selectionEnd() const;
201         /**
202          * Update the selection status and save permanent
203          * selection if needed.
204          * @param selecting the new selection status
205          * @return whether the selection status has changed
206          */
207         bool selHandle(bool selecting);
208         ///
209         docstring selectionAsString(bool with_label) const;
210         ///
211         docstring currentState() const;
212
213         /// auto-correct mode
214         bool autocorrect() const { return autocorrect_; }
215         /// auto-correct mode
216         bool & autocorrect() { return autocorrect_; }
217         /// are we entering a macro name?
218         bool macromode() const { return macromode_; }
219         /// are we entering a macro name?
220         bool & macromode() { return macromode_; }
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);
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         // FIXME: this can't be a const & and a const function because
300         // LFUN_TAB_* wants to move the real anchor.
301         /// access to real selection anchor
302         DocIterator & realAnchor();
303         /// sets anchor to cursor position
304         void resetAnchor();
305         /// access to owning BufferView
306         BufferView & bv() const;
307         /// get some interesting description of top position
308         void info(odocstream & os) const;
309         /// are we in math mode (2), text mode (1) or unsure (0)?
310         int currentMode();
311         /// reset cursor bottom to the beginning of the top inset
312         // (sort of 'chroot' environment...)
313         void reset();
314         /// for spellchecking
315         void replaceWord(std::string const & replacestring);
316         /**
317          * the event was not (yet) dispatched.
318          *
319          * Should only be called by an inset's doDispatch() method. It means:
320          * I, the doDispatch() method of InsetFoo, hereby declare that I am
321          * not able to handle that request and trust my parent will do the
322          * Right Thing (even if my getStatus partner said that I can do it).
323          * It is sort of a kludge that should be used only rarely...
324          */
325         void undispatched() const;
326         /// the event was already dispatched
327         void dispatched() const;
328         /// Set which screen update should be done
329         void screenUpdateFlags(Update::flags f) const;
330         /// Forces an updateBuffer() call
331         void forceBufferUpdate() const;
332         /// Removes any pending updateBuffer() call
333         void clearBufferUpdate() const;
334         /// Do we need to call updateBuffer()?
335         bool needBufferUpdate() const;
336         /**
337          * don't call update() when done
338          *
339          * Should only be called by an inset's doDispatch() method. It means:
340          * I handled that request and I can reassure you that the screen does
341          * not need to be re-drawn and all entries in the coord cache stay
342          * valid (and there are no other things to put in the coord cache).
343          * This is a fairly rare event as well and only some optimization.
344          * Not using noScreenUpdate() should never be wrong.
345          */
346         void noScreenUpdate() const;
347         /// fix cursor in circumstances that should never happen.
348         /// \retval true if a fix occurred.
349         bool fixIfBroken();
350         /// Repopulate the slices insets from bottom to top. Useful
351         /// for stable iterators or Undo data.
352         void sanitize();
353
354         ///
355         bool textUndo();
356         ///
357         bool textRedo();
358
359         /// makes sure the next operation will be stored
360         void finishUndo() const;
361
362         /// open a new group of undo operations. Groups can be nested.
363         void beginUndoGroup() const;
364
365         /// end the current undo group
366         void endUndoGroup() const;
367
368         /// The general case: prepare undo for an arbitrary range.
369         void recordUndo(pit_type from, pit_type to) const;
370
371         /// Convenience: prepare undo for the range between 'from' and cursor.
372         void recordUndo(pit_type from) const;
373
374         /// Convenience: prepare undo for the single paragraph or cell
375         /// containing the cursor
376         void recordUndo(UndoKind kind = ATOMIC_UNDO) const;
377
378         /// Convenience: prepare undo for the inset containing the cursor
379         void recordUndoInset(Inset const * inset = 0) const;
380
381         /// Convenience: prepare undo for the whole buffer
382         void recordUndoFullBuffer() const;
383
384         /// Convenience: prepare undo for buffer parameters
385         void recordUndoBufferParams() const;
386
387         /// Convenience: prepare undo for the selected paragraphs or cells
388         void recordUndoSelection() const;
389
390         ///
391         void checkBufferStructure();
392
393         /// hook for text input to maintain the "new born word"
394         void markNewWordPosition();
395
396         /// The position of the new born word
397         /// As the user is entering a word without leaving it
398         /// the result is not empty. When not in text mode
399         /// and after leaving the word the result is empty.
400         DocIterator newWord() const { return new_word_; }
401
402 public:
403 //private:
404         
405         ///
406         DocIterator const & beforeDispatchCursor() const { return beforeDispatchCursor_; }
407         ///
408         void saveBeforeDispatchPosXY();
409
410 private:
411         /// validate the "new born word" position
412         void checkNewWordPosition();
413         /// clear the "new born word" position
414         void clearNewWordPosition();
415
416 private:
417         ///
418         BufferView * bv_;
419         ///
420         mutable DispatchResult disp_;
421         /**
422          * The target x position of the cursor. This is used for when
423          * we have text like :
424          *
425          * blah blah blah blah| blah blah blah
426          * blah blah blah
427          * blah blah blah blah blah blah
428          *
429          * When we move onto row 3, we would like to be vertically aligned
430          * with where we were in row 1, despite the fact that row 2 is
431          * shorter than x()
432          */
433         int x_target_;
434         /// if a x_target cannot be hit exactly in a text, put the difference here
435         int textTargetOffset_;
436         /// the start of the new born word
437         DocIterator new_word_;
438         /// position before dispatch started
439         DocIterator beforeDispatchCursor_;
440         /// cursor screen coordinates before dispatch started
441         int beforeDispatchPosX_;
442         int beforeDispatchPosY_;
443
444 ///////////////////////////////////////////////////////////////////
445 //
446 // The part below is the non-integrated rest of the original math
447 // cursor. This should be either generalized for texted or moved
448 // back to the math insets.
449 //
450 ///////////////////////////////////////////////////////////////////
451
452 public:
453         ///
454         void insert(MathAtom const &);
455         ///
456         void insert(MathData const &);
457         /// return false for empty math insets
458         bool erase();
459         /// return false for empty math insets
460         bool backspace();
461         /// move the cursor up by sending an internal LFUN_UP
462         /// return true if fullscreen update is needed
463         bool up();
464         /// move the cursor up by sending an internal LFUN_DOWN,
465         /// return true if fullscreen update is needed
466         bool down();
467         /// whether the cursor is either at the first or last row
468         bool atFirstOrLastRow(bool up);
469         /// move up/down in a text inset, called for LFUN_UP/DOWN,
470         /// return true if successful, updateNeeded set to true if fullscreen
471         /// update is needed, otherwise it's not touched
472         bool upDownInText(bool up, bool & updateNeeded);
473         /// move up/down in math or any non text inset, call for LFUN_UP/DOWN
474         /// return true if successful
475         bool upDownInMath(bool up);
476         ///
477         void plainErase();
478         ///
479         void plainInsert(MathAtom const & at);
480         ///
481         void niceInsert(MathAtom const & at);
482         /// return the number of inserted array items
483         int niceInsert(docstring const & str, Parse::flags f = Parse::NORMAL,
484                         bool enter = true);
485
486         /// in pixels from top of screen
487         void setScreenPos(int x, int y);
488         /// current offset in the top cell
489
490         /// interpret name a name of a macro. Returns true if
491         /// something got inserted.
492         bool macroModeClose();
493         /// are we currently typing the name of a macro?
494         bool inMacroMode() const;
495         /// get access to the macro we are currently typing
496         InsetMathUnknown * activeMacro();
497         /// get access to the macro we are currently typing
498         InsetMathUnknown const * activeMacro() const;
499
500         /// replace selected stuff with at, placing the former
501         // selection in given cell of atom
502         void handleNest(MathAtom const & at, int cell = 0);
503         ///
504         bool isInside(Inset const *) const;
505
506         /// make sure cursor position is valid
507         /// FIXME: It does a subset of fixIfBroken. Maybe merge them?
508         void normalize();
509         /// mark current cursor trace for redraw
510         void touch();
511
512         /// hack for reveal codes
513         void markInsert();
514         void markErase();
515         /// injects content of a cell into parent
516         void pullArg();
517         /// split font inset etc
518         void handleFont(std::string const & font);
519
520         /// display a message
521         void message(docstring const & msg) const;
522         /// display an error message
523         void errorMessage(docstring const & msg) const;
524         ///
525         docstring getPossibleLabel() const;
526
527         /// the name of the macro we are currently inputting
528         docstring macroName();
529         /// where in the curent cell does the macro name start?
530         int macroNamePos();
531         /// can we enter the inset?
532         bool openable(MathAtom const &) const;
533         ///
534         Encoding const * getEncoding() const;
535         /// font at cursor position
536         Font getFont() const;
537 };
538
539
540 /**
541  * Notifies all insets which appear in old, but not in cur. And then
542  * notify all insets which appear in cur, but not in old.
543  * Make sure that the cursor old is valid, i.e. all inset pointers
544  * point to valid insets! Use Cursor::fixIfBroken if necessary.
545  */
546 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur);
547
548
549 } // namespace lyx
550
551 #endif // LYXLCURSOR_H