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