]> git.lyx.org Git - lyx.git/blob - src/Cursor.h
fix multirow/column logic in table dialog
[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         /// 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         /// Repopulate the slices insets from bottom to top. Useful
310         /// for stable iterators or Undo data.
311         void sanitize();
312
313         /// output
314         friend std::ostream & operator<<(std::ostream & os, Cursor const & cur);
315         friend LyXErr & operator<<(LyXErr & os, Cursor const & cur);
316
317         ///
318         bool textUndo();
319         ///
320         bool textRedo();
321
322         /// makes sure the next operation will be stored
323         void finishUndo() const;
324
325         /// open a new group of undo operations. Groups can be nested.
326         void beginUndoGroup() const;
327
328         /// end the current undo group
329         void endUndoGroup() const;
330
331         /// The general case: prepare undo for an arbitrary range.
332         void recordUndo(UndoKind kind, pit_type from, pit_type to) const;
333
334         /// Convenience: prepare undo for the range between 'from' and cursor.
335         void recordUndo(UndoKind kind, pit_type from) const;
336
337         /// Convenience: prepare undo for the single paragraph or cell
338         /// containing the cursor
339         void recordUndo(UndoKind kind = ATOMIC_UNDO) const;
340
341         /// Convenience: prepare undo for the inset containing the cursor
342         void recordUndoInset(UndoKind kind = ATOMIC_UNDO,
343                              Inset const * inset = 0) const;
344
345         /// Convenience: prepare undo for the whole buffer
346         void recordUndoFullDocument() const;
347
348         /// Convenience: prepare undo for the selected paragraphs or cells
349         void recordUndoSelection() const;
350
351         ///
352         void checkBufferStructure();
353
354         /// hook for text input to maintain the "new born word"
355         void markNewWordPosition();
356
357         /// The position of the new born word
358         /// As the user is entering a word without leaving it
359         /// the result is not empty. When not in text mode
360         /// and after leaving the word the result is empty.
361         DocIterator newWord() const { return new_word_; }
362
363 public:
364 //private:
365         
366         ///
367         DocIterator const & beforeDispatchCursor() const { return beforeDispatchCursor_; }
368         ///
369         void saveBeforeDispatchPosXY();
370
371 private:
372         /// validate the "new born word" position
373         void checkNewWordPosition();
374         /// clear the "new born word" position
375         void clearNewWordPosition();
376
377 private:
378         ///
379         BufferView * bv_;
380         ///
381         mutable DispatchResult disp_;
382         /**
383          * The target x position of the cursor. This is used for when
384          * we have text like :
385          *
386          * blah blah blah blah| blah blah blah
387          * blah blah blah
388          * blah blah blah blah blah blah
389          *
390          * When we move onto row 3, we would like to be vertically aligned
391          * with where we were in row 1, despite the fact that row 2 is
392          * shorter than x()
393          */
394         int x_target_;
395         /// if a x_target cannot be hit exactly in a text, put the difference here
396         int textTargetOffset_;
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