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