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