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