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