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