]> git.lyx.org Git - lyx.git/blob - src/Cursor.h
Adapt citengine to current layout format.
[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(bool devel_mode) 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 x,y position
220         void getPos(int & x, int & y) const;
221         /// return logical positions between which the cursor is situated
222         /**
223          * If the cursor is at the edge of a row, the position which is "over the
224          * edge" will be returned as -1.
225          */
226         void getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const;
227         /// the row in the paragraph we're in
228         Row const & textRow() const;
229
230         //
231         // common part
232         //
233         /// move visually one step to the right
234         /**
235          * @note: This method may move into an inset unless skip_inset == true.
236          * @note: This method may move into a new paragraph.
237          * @note: This method may move out of the current slice.
238          * @return: true if moved, false if not moved
239          */
240         bool posVisRight(bool skip_inset = false);
241         /// move visually one step to the left
242         /**
243          * @note: This method may move into an inset unless skip_inset == true.
244          * @note: This method may move into a new paragraph.
245          * @note: This method may move out of the current slice.
246          * @return: true if moved, false if not moved
247          */
248         bool posVisLeft(bool skip_inset = false);
249         /// move visually to next/previous row
250         /**
251          * Assuming we were to keep moving left (right) from the current cursor
252          * position, place the cursor at the rightmost (leftmost) edge of the
253          * new row to which we would move according to visual-mode cursor movement.
254          * This could be either the next or the previous row, depending on the
255          * direction in which we're moving, and whether we're in an LTR or RTL
256          * paragraph.
257          * @note: The new position may even be in a new paragraph.
258          * @note: This method will not move out of the current slice.
259          * @return: false if not moved (no more rows to move to in given direction)
260          * @return: true if moved
261          */
262         bool posVisToNewRow(bool movingLeft);
263         /// move to right or left extremity of the current row
264         void posVisToRowExtremity(bool left);
265         /// Should interpretation of the arrow keys be reversed?
266         bool reverseDirectionNeeded() const;
267
268         /// insert an inset
269         void insert(Inset *);
270         /// insert a single char
271         void insert(char_type c);
272         /// insert a string
273         void insert(docstring const & str);
274
275         /// FIXME: rename to something sensible showing difference to x_target()
276         /// in pixels from left of screen, set to current position if unset
277         int targetX() const;
278         /// set the targetX to x
279         void setTargetX(int x);
280         /// return targetX or -1 if unset
281         int x_target() const;
282         /// set targetX to current position
283         void setTargetX();
284         /// clear targetX, i.e. set it to -1
285         void clearTargetX();
286         /// set offset to actual position - targetX
287         void updateTextTargetOffset();
288         /// distance between actual and targeted position during last up/down in text
289         int textTargetOffset() const;
290
291         /// access to normalized selection anchor
292         CursorSlice normalAnchor() const;
293         /// access to real selection anchor
294         DocIterator const & realAnchor() const { return anchor_; }
295         DocIterator & realAnchor() { return anchor_; }
296         /// sets anchor to cursor position
297         void resetAnchor();
298         /// access to owning BufferView
299         BufferView & bv() const;
300         /// get some interesting description of top position
301         void info(odocstream & os, bool devel_mode) const;
302         /// are we in math mode (2), text mode (1) or unsure (0)?
303         int currentMode();
304         /// reset cursor bottom to the beginning of the top inset
305         // (sort of 'chroot' environment...)
306         void reset();
307         /// for spellchecking
308         void replaceWord(std::string const & replacestring);
309         /**
310          * the event was not (yet) dispatched.
311          *
312          * Should only be called by an inset's doDispatch() method. It means:
313          * I, the doDispatch() method of InsetFoo, hereby declare that I am
314          * not able to handle that request and trust my parent will do the
315          * Right Thing (even if my getStatus partner said that I can do it).
316          * It is sort of a kludge that should be used only rarely...
317          */
318         void undispatched() const;
319         /// the event was already dispatched
320         void dispatched() const;
321         /// Set which screen update should be done
322         void screenUpdateFlags(Update::flags f) const;
323         /// Forces an updateBuffer() call
324         void forceBufferUpdate() const;
325         /// Removes any pending updateBuffer() call
326         void clearBufferUpdate() const;
327         /// Do we need to call updateBuffer()?
328         bool needBufferUpdate() const;
329         /**
330          * don't call update() when done
331          *
332          * Should only be called by an inset's doDispatch() method. It means:
333          * I handled that request and I can reassure you that the screen does
334          * not need to be re-drawn and all entries in the coord cache stay
335          * valid (and there are no other things to put in the coord cache).
336          * This is a fairly rare event as well and only some optimization.
337          * Not using noScreenUpdate() should never be wrong.
338          */
339         void noScreenUpdate() const;
340         /// fix cursor in circumstances that should never happen.
341         /// \retval true if a fix occurred.
342         bool fixIfBroken();
343         /// Repopulate the slices insets from bottom to top. Useful
344         /// for stable iterators or Undo data.
345         void sanitize();
346
347         ///
348         bool textUndo();
349         ///
350         bool textRedo();
351
352         /// makes sure the next operation will be stored
353         void finishUndo() const;
354
355         /// open a new group of undo operations. Groups can be nested.
356         void beginUndoGroup() const;
357
358         /// end the current undo group
359         void endUndoGroup() const;
360
361         /// The general case: prepare undo for an arbitrary range.
362         void recordUndo(pit_type from, pit_type to) const;
363
364         /// Convenience: prepare undo for the range between 'from' and cursor.
365         void recordUndo(pit_type from) const;
366
367         /// Convenience: prepare undo for the single paragraph or cell
368         /// containing the cursor
369         void recordUndo(UndoKind kind = ATOMIC_UNDO) const;
370
371         /// Convenience: prepare undo for the inset containing the cursor
372         void recordUndoInset(Inset const * inset = 0) const;
373
374         /// Convenience: prepare undo for the whole buffer
375         void recordUndoFullBuffer() const;
376
377         /// Convenience: prepare undo for buffer parameters
378         void recordUndoBufferParams() const;
379
380         /// Convenience: prepare undo for the selected paragraphs or cells
381         void recordUndoSelection() const;
382
383         ///
384         void checkBufferStructure();
385
386         /// hook for text input to maintain the "new born word"
387         void markNewWordPosition();
388
389         /// The position of the new born word
390         /// As the user is entering a word without leaving it
391         /// the result is not empty. When not in text mode
392         /// and after leaving the word the result is empty.
393         DocIterator newWord() const { return new_word_; }
394
395         /// Return true if the next or previous inset has confirmDeletion depending
396         /// on the boolean before. If there is a selection, return true if at least
397         /// one inset in the selection has confirmDeletion.
398         bool confirmDeletion(bool before = false) const;
399
400         /// Determine if x falls to the left or to the side of the middle of the
401         /// inset, and advance the cursor to match this position. If edit is true,
402         /// keep the cursor in front of the inset if it matter for dialogs.
403         /// Note: it does not handle RTL text yet, and is only used in math for now.
404         void moveToClosestEdge(int x, bool edit = false);
405
406 public:
407 //private:
408
409         ///
410         DocIterator const & beforeDispatchCursor() const { return beforeDispatchCursor_; }
411         ///
412         void saveBeforeDispatchPosXY();
413
414 private:
415         /// validate the "new born word" position
416         void checkNewWordPosition();
417         /// clear the "new born word" position
418         void clearNewWordPosition();
419
420 private:
421         ///
422         BufferView * bv_;
423         ///
424         mutable DispatchResult disp_;
425         /**
426          * The target x position of the cursor. This is used for when
427          * we have text like :
428          *
429          * blah blah blah blah| blah blah blah
430          * blah blah blah
431          * blah blah blah blah blah blah
432          *
433          * When we move onto row 3, we would like to be vertically aligned
434          * with where we were in row 1, despite the fact that row 2 is
435          * shorter than x()
436          */
437         int x_target_;
438         /// if a x_target cannot be hit exactly in a text, put the difference here
439         int textTargetOffset_;
440         /// the start of the new born word
441         DocIterator new_word_;
442         /// position before dispatch started
443         DocIterator beforeDispatchCursor_;
444         /// cursor screen coordinates before dispatch started
445         int beforeDispatchPosX_;
446         int beforeDispatchPosY_;
447
448 ///////////////////////////////////////////////////////////////////
449 //
450 // The part below is the non-integrated rest of the original math
451 // cursor. This should be either generalized for texted or moved
452 // back to the math insets.
453 //
454 ///////////////////////////////////////////////////////////////////
455
456 public:
457         ///
458         void insert(MathAtom const &);
459         ///
460         void insert(MathData const &);
461         /// return false for empty math insets
462         /// Use force to skip the confirmDeletion check.
463         bool erase(bool force = false);
464         bool backspace(bool force = false);
465
466         /// move the cursor up by sending an internal LFUN_UP
467         /// return true if fullscreen update is needed
468         bool up();
469         /// move the cursor up by sending an internal LFUN_DOWN,
470         /// return true if fullscreen update is needed
471         bool down();
472         /// whether the cursor is either at the first or last row
473         bool atFirstOrLastRow(bool up);
474         /// move up/down in a text inset, called for LFUN_UP/DOWN,
475         /// return true if successful, updateNeeded set to true if fullscreen
476         /// update is needed, otherwise it's not touched
477         bool upDownInText(bool up, bool & updateNeeded);
478         /// move up/down in math or any non text inset, call for LFUN_UP/DOWN
479         /// return true if successful
480         bool upDownInMath(bool up);
481         ///
482         InsetMath & nextMath();
483         ///
484         InsetMath & prevMath();
485         /// move forward in math. word: whether to skip a whole "word" (insets with
486         /// the same mathclass)
487         bool mathForward(bool word);
488         ///
489         bool mathBackward(bool word);
490         ///
491         void plainErase();
492         ///
493         void plainInsert(MathAtom const & at);
494         ///
495         void niceInsert(MathAtom const & at);
496         /// return the number of inserted array items
497         int niceInsert(docstring const & str, Parse::flags f = Parse::NORMAL,
498                         bool enter = true);
499
500         /// in pixels from top of screen
501         void setScreenPos(int x, int y);
502         /// current offset in the top cell
503
504         /// interpret name a name of a macro. Returns true if
505         /// something got inserted.
506         bool macroModeClose();
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
514         /// replace selected stuff with at, placing the former
515         // selection in given cell of atom
516         void handleNest(MathAtom const & at, int cell = 0);
517         ///
518         bool isInside(Inset const *) const;
519
520         /// make sure cursor position is valid
521         /// FIXME: It does a subset of fixIfBroken. Maybe merge them?
522         void normalize();
523         /// mark current cursor trace for redraw
524         void touch();
525
526         /// hack for reveal codes
527         void markInsert();
528         void markErase();
529         /// injects content of a cell into parent
530         void pullArg();
531         /// split font inset etc
532         void handleFont(std::string const & font);
533
534         /// display a message
535         void message(docstring const & msg) const;
536         /// display an error message
537         void errorMessage(docstring const & msg) const;
538         ///
539         docstring getPossibleLabel() const;
540
541         /// the name of the macro we are currently inputting
542         docstring macroName();
543         /// where in the curent cell does the macro name start?
544         int macroNamePos();
545         /// can we enter the inset?
546         bool openable(MathAtom const &) const;
547         ///
548         Encoding const * getEncoding() const;
549         /// font at cursor position
550         Font getFont() const;
551 };
552
553
554 /**
555  * Notifies all insets which appear in \c old, but not in \c cur. And then
556  * notify all insets which appear in \c cur, but not in \c old.
557  * \returns true if cursor is now invalid, e.g. if some insets in
558  *   higher cursor slices of \c old do not exist anymore. In this case
559  *   it may be necessary to use Use Cursor::fixIfBroken.
560  */
561 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur);
562
563
564 } // namespace lyx
565
566 #endif // LYXLCURSOR_H