]> git.lyx.org Git - features.git/blob - src/Cursor.h
Set language to OS input language when moving cursor
[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 /*
13 First some explanation about what a Cursor really is, from local to
14 global.
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 text)
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. For a InsetTabular,
24     this is the tabular itself, not the cell inset (which is an
25     InsetTableCell).
26
27 * a DocIterator indicated the position of the cursor in the document.
28   It knows about the current buffer (buffer() method) and contains a
29   vector of CursorSlices that describes the nesting of insets up to the
30   point of interest. Note that operator<< has been implemented, so that
31   one can send a DocIterator to a stream to see its value. Try it, it is
32   very helpful to understand the cursor layout.
33   * when using idx/pit/pos on a DocIterator, one gets the information
34     from the inner slice (this slice can be accessed as top())
35   * inMathed() returns true when the cursor is in a math formula
36   * inTexted() returns true when the cursor is in text
37   * innerTextSlice() returns the deepest slice that is text (useful
38     when one is in a math equation and looks for the enclosing text)
39
40 * A CursorData is a descendant of Dociterator that contains
41   * a second DocIterator object, the anchor, that is useful when
42     selecting.
43   * some other data that describes current selection, cursor font, etc.
44
45   This class is mostly used only for undo and contains the Cursor
46   elements that are not GUI-related. In LyX 2.0, Cursor was directly
47   deriving from DocIterator
48
49 * A Cursor is a descendant of CursorData that contains interesting
50   display-related information, in particular the BufferView that owns it.
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
75 /**
76  * This class describes the position of a cursor within a document,
77  * but does not contain any detail about the view. It is currently
78  * only used to save cursor position in Undo, but culd be extended to
79  * handle the methods that only need this data.
80  **/
81 class CursorData : public DocIterator
82 {
83 public:
84         ///
85         CursorData();
86         ///
87         explicit CursorData(Buffer * buffer);
88         ///
89         explicit CursorData(DocIterator const & dit);
90         /// output
91         friend std::ostream & operator<<(std::ostream & os, CursorData const & cur);
92         friend LyXErr & operator<<(LyXErr & os, CursorData const & cur);
93
94         /// reset cursor bottom to the beginning of the top inset
95         // (sort of 'chroot' environment...)
96         void reset();
97         /// sets cursor part
98         /// this (intentionally) does neither touch anchor nor selection status
99         void setCursor(DocIterator const & it);
100         /// set the cursor to dit normalised against the anchor, and set selection.
101         void setCursorSelectionTo(DocIterator dit);
102         /// sets the cursor to the normalized selection anchor
103         void setCursorToAnchor();
104
105         //
106         // selection
107         //
108         /// selection active?
109         bool selection() const { return selection_; }
110         /// set selection; this is lower level than (set|clear)Selection
111         void selection(bool sel) { selection_ = sel; }
112         /// do we have a multicell selection?
113         bool selIsMultiCell() const
114                 { return selection_ && selBegin().idx() != selEnd().idx(); }
115         /// do we have a multiline selection?
116         bool selIsMultiLine() const
117                 { return selection_ && selBegin().pit() != selEnd().pit(); }
118         ///
119         void setWordSelection(bool set) { word_selection_ = set; }
120         ///
121         bool wordSelection() { return word_selection_; }
122         /// did we place the anchor?
123         bool mark() const { return mark_; }
124         /// did we place the anchor?
125         void setMark(bool mark) { mark_ = mark; }
126         ///
127         void setSelection();
128         /// set selection at given position
129         void setSelection(DocIterator const & where, int n);
130         ///
131         void clearSelection();
132         /// check whether selection contains specific type of inset
133         /// returns 0 if no selection was made
134         bool insetInSelection(InsetCode const & inset);
135         /// count occurences of specific inset type in the selection
136         /// returns 0 if no selection was made
137         int countInsetsInSelection(InsetCode const & inset);
138
139         /// access to normalized selection anchor
140         CursorSlice normalAnchor() const;
141         /// access to real selection anchor
142         DocIterator const & realAnchor() const { return anchor_; }
143         DocIterator & realAnchor() { return anchor_; }
144         /// sets anchor to cursor position
145         void resetAnchor();
146
147         /// access start of selection
148         CursorSlice selBegin() const;
149         /// access end of selection
150         CursorSlice selEnd() const;
151         /// access start of selection
152         DocIterator selectionBegin() const;
153         /// access end of selection
154         DocIterator selectionEnd() const;
155
156         ///
157         docstring selectionAsString(bool with_label) const;
158         /// get some interesting description of top position
159         void info(odocstream & os, bool devel_mode) const;
160         ///
161         docstring currentState(bool devel_mode) const;
162
163         /// fix cursor in circumstances that should never happen.
164         /// \retval true if a fix occurred.
165         bool fixIfBroken();
166         /// Repopulate the slices insets from bottom to top. Useful
167         /// for stable iterators or Undo data.
168         void sanitize();
169
170         ///
171         bool undoAction();
172         ///
173         bool redoAction();
174
175         /// makes sure the next operation will be stored
176         void finishUndo() const;
177         /// open a new group of undo operations. Groups can be nested.
178         void beginUndoGroup() const;
179         /// end the current undo group
180         void endUndoGroup() const;
181         /// end abruptly the current group and create a new one wih the same nesting level
182         void splitUndoGroup() const;
183
184         /// The general case: prepare undo for an arbitrary range.
185         void recordUndo(pit_type from, pit_type to) const;
186         /// Convenience: prepare undo for the range between 'from' and cursor.
187         void recordUndo(pit_type from) const;
188         /// Convenience: prepare undo for the single paragraph or cell
189         /// containing the cursor
190         void recordUndo(UndoKind kind = ATOMIC_UNDO) const;
191         /// Convenience: prepare undo for the inset containing the cursor
192         void recordUndoInset(Inset const * inset = 0) const;
193         /// Convenience: prepare undo for the whole buffer
194         void recordUndoFullBuffer() const;
195         /// Convenience: prepare undo for buffer parameters
196         void recordUndoBufferParams() const;
197         /// Convenience: prepare undo for the selected paragraphs or cells
198         void recordUndoSelection() const;
199
200         /// hook for text input to maintain the "new born word"
201         void markNewWordPosition();
202         /// The position of the new born word
203         /// As the user is entering a word without leaving it
204         /// the result is not empty. When not in text mode
205         /// and after leaving the word the result is empty.
206         DocIterator newWord() const { return new_word_; }
207
208         /// are we in math mode (2), text mode (1) or unsure (0)?
209         int currentMode();
210
211         /// Return true if the next or previous inset has confirmDeletion depending
212         /// on the boolean before. If there is a selection, return true if at least
213         /// one inset in the selection has confirmDeletion.
214         bool confirmDeletion(bool before = false) const;
215
216 private:
217         /// validate the "new born word" position
218         void checkNewWordPosition();
219         /// clear the "new born word" position
220         void clearNewWordPosition();
221
222         /// the anchor position
223         DocIterator anchor_;
224         /// do we have a selection?
225         bool selection_;
226         /// are we on the way to get one?
227         bool mark_;
228         /// are we in word-selection mode? This is set when double clicking.
229         bool word_selection_;
230
231         /// the start of the new born word
232         DocIterator new_word_;
233         //
234         // math specific stuff that could be promoted to "global" later
235         //
236
237         // FIXME: make them private
238 public:
239         /// The current font settings. This holds the settings for output.
240         Font current_font;
241         /// The current display font. This holds the settings of the text
242         /// in the workarea.
243         Font real_current_font;
244 };
245
246
247 /// The cursor class describes the position of a cursor within a document.
248 class Cursor : public CursorData
249 {
250 public:
251         /// create the cursor of a BufferView
252         explicit Cursor(BufferView & bv);
253
254         /// add a new cursor slice
255         void push(Inset & inset);
256         /// add a new cursor slice, place cursor at front (move backwards)
257         void pushBackward(Inset & inset);
258         /// try to put cursor in inset before it in entry cell, or next one
259         /// if it is not empty, or exit the slice if there is no next one.
260         void editInsertedInset();
261
262         /// pop one level off the cursor
263         void pop();
264         /// pop one slice off the cursor stack and go backwards
265         bool popBackward();
266         /// pop one slice off the cursor stack and go forward
267         bool popForward();
268         /// set the cursor data
269         void setCursorData(CursorData const & data);
270
271         /// returns true if we made a decision
272         bool getStatus(FuncRequest const & cmd, FuncStatus & flag) const;
273         /// dispatch from innermost inset upwards
274         void dispatch(FuncRequest const & cmd);
275         /// display a message
276         void message(docstring const & msg) const;
277         /// display an error message
278         void errorMessage(docstring const & msg) const;
279         /// get the resut of the last dispatch
280         DispatchResult const & result() const;
281
282         /// Set the cursor language from current input method language
283         /* Considers first exact math with the codes used in the document,
284          * then approximate match among the same list, and finally exact
285          * or partial match with the whole list of languages.
286          */
287         void setLanguageFromInput();
288         /// Set the current font of the cursor from its location. 
289         void setCurrentFont();
290
291         /**
292          * Update the selection status and save permanent
293          * selection if needed.
294          * @param selecting the new selection status
295          * @return whether the selection status has changed
296          */
297         bool selHandle(bool selecting);
298
299         /// returns x,y position
300         void getPos(int & x, int & y) const;
301         /// return logical positions between which the cursor is situated
302         /**
303          * If the cursor is at the edge of a row, the position which is "over the
304          * edge" will be returned as -1.
305          */
306         void getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const;
307         /// the row in the paragraph we're in
308         Row const & textRow() const;
309
310         //
311         // common part
312         //
313         /// move visually one step to the right
314         /**
315          * @note: This method may move into an inset unless skip_inset == true.
316          * @note: This method may move into a new paragraph.
317          * @note: This method may move out of the current slice.
318          * @return: true if moved, false if not moved
319          */
320         bool posVisRight(bool skip_inset = false);
321         /// move visually one step to the left
322         /**
323          * @note: This method may move into an inset unless skip_inset == true.
324          * @note: This method may move into a new paragraph.
325          * @note: This method may move out of the current slice.
326          * @return: true if moved, false if not moved
327          */
328         bool posVisLeft(bool skip_inset = false);
329         /// move visually to next/previous row
330         /**
331          * Assuming we were to keep moving left (right) from the current cursor
332          * position, place the cursor at the rightmost (leftmost) edge of the
333          * new row to which we would move according to visual-mode cursor movement.
334          * This could be either the next or the previous row, depending on the
335          * direction in which we're moving, and whether we're in an LTR or RTL
336          * paragraph.
337          * @note: The new position may even be in a new paragraph.
338          * @note: This method will not move out of the current slice.
339          * @return: false if not moved (no more rows to move to in given direction)
340          * @return: true if moved
341          */
342         bool posVisToNewRow(bool movingLeft);
343         /// move to right or left extremity of the current row
344         void posVisToRowExtremity(bool left);
345         /// Should interpretation of the arrow keys be reversed?
346         bool reverseDirectionNeeded() const;
347
348         ///
349         ///  Insertion (mathed and texted)
350         ///
351         /// insert a single char
352         void insert(char_type c);
353         /// insert a string
354         void insert(docstring const & str);
355         /// insert an inset
356         void insert(Inset *);
357         ///
358         ///  Insertion (mathed only)
359         ///
360         /// insert a math atom
361         void insert(MathAtom const &);
362         /// insert a string of atoms
363         void insert(MathData const &);
364         /// Like insert, but moves the selection inside the inset if possible
365         void niceInsert(MathAtom const & at);
366         /// return the number of inserted array items
367         /// FIXME: document properly
368         int niceInsert(docstring const & str, Parse::flags f = Parse::NORMAL,
369                         bool enter = true);
370
371         /// FIXME: rename to something sensible showing difference to x_target()
372         /// in pixels from left of screen, set to current position if unset
373         int targetX() const;
374         /// set the targetX to x
375         void setTargetX(int x);
376         /// return targetX or -1 if unset
377         int x_target() const;
378         /// set targetX to current position
379         void setTargetX();
380         /// clear targetX, i.e. set it to -1
381         void clearTargetX();
382         /// set offset to actual position - targetX
383         void updateTextTargetOffset();
384         /// distance between actual and targeted position during last up/down in text
385         int textTargetOffset() const;
386
387         /// access to owning BufferView
388         BufferView & bv() const;
389         /// reset cursor bottom to the beginning of the top inset
390         // (sort of 'chroot' environment...)
391         void reset();
392
393         /**
394          * the event was not (yet) dispatched.
395          *
396          * Should only be called by an inset's doDispatch() method. It means:
397          * I, the doDispatch() method of InsetFoo, hereby declare that I am
398          * not able to handle that request and trust my parent will do the
399          * Right Thing (even if my getStatus partner said that I can do it).
400          * It is sort of a kludge that should be used only rarely...
401          */
402         void undispatched() const;
403         /// the event was already dispatched
404         void dispatched() const;
405
406         /// Describe the screen update that should be done
407         void screenUpdateFlags(Update::flags f) const;
408         /**
409          * Reset update flags to Update::None.
410          *
411          * Should only be called by an inset's doDispatch() method. It means:
412          * I handled that request and I can reassure you that the screen does
413          * not need to be re-drawn and all entries in the coord cache stay
414          * valid (and there are no other things to put in the coord cache).
415          * This is a fairly rare event as well and only some optimization.
416          * Not using noScreenUpdate() should never be wrong.
417          */
418         void noScreenUpdate() const;
419
420         /// Forces an updateBuffer() call
421         void forceBufferUpdate() const;
422         /// Removes any pending updateBuffer() call
423         void clearBufferUpdate() const;
424         /// Do we need to call updateBuffer()?
425         bool needBufferUpdate() const;
426
427         /// Repopulate the slices insets from bottom to top. Useful
428         /// for stable iterators or Undo data.
429         void sanitize();
430
431         ///
432         void checkBufferStructure();
433
434         /// Determine if x falls to the left or to the side of the middle of the
435         /// inset, and advance the cursor to match this position. If edit is true,
436         /// keep the cursor in front of the inset if it matter for dialogs.
437         /// Note: it does not handle RTL text yet, and is only used in math for now.
438         void moveToClosestEdge(int x, bool edit = false);
439
440         /// whether the cursor is either at the first or last row
441         bool atFirstOrLastRow(bool up);
442
443 public:
444 //private:
445
446         ///
447         DocIterator const & beforeDispatchCursor() const { return beforeDispatchCursor_; }
448         ///
449         void saveBeforeDispatchPosXY();
450
451 private:
452         ///
453         BufferView * bv_;
454         ///
455         mutable DispatchResult disp_;
456         /**
457          * The target x position of the cursor. This is used for when
458          * we have text like :
459          *
460          * blah blah blah blah| blah blah blah
461          * blah blah blah
462          * blah blah blah blah blah blah
463          *
464          * When we move onto row 3, we would like to be vertically aligned
465          * with where we were in row 1, despite the fact that row 2 is
466          * shorter than x()
467          */
468         int x_target_;
469         /// if a x_target cannot be hit exactly in a text, put the difference here
470         int textTargetOffset_;
471         /// position before dispatch started
472         DocIterator beforeDispatchCursor_;
473         /// cursor screen coordinates before dispatch started
474         int beforeDispatchPosX_;
475         int beforeDispatchPosY_;
476
477 ///////////////////////////////////////////////////////////////////
478 //
479 // The part below is the non-integrated rest of the original math
480 // cursor. This should be either generalized for texted or moved
481 // back to the math insets.
482 //
483 ///////////////////////////////////////////////////////////////////
484
485 public:
486         /// return false for empty math insets
487         /// Use force to skip the confirmDeletion check.
488         bool erase(bool force = false);
489         bool backspace(bool force = false);
490
491         /// move the cursor up by sending an internal LFUN_UP
492         /// return true if fullscreen update is needed
493         bool up();
494         /// move the cursor up by sending an internal LFUN_DOWN,
495         /// return true if fullscreen update is needed
496         bool down();
497         /// move up/down in a text inset, called for LFUN_UP/DOWN,
498         /// return true if successful, updateNeeded set to true if fullscreen
499         /// update is needed, otherwise it's not touched
500         bool upDownInText(bool up, bool & updateNeeded);
501         /// move up/down in math or any non text inset, call for LFUN_UP/DOWN
502         /// return true if successful
503         bool upDownInMath(bool up);
504         /// move forward in math. word: whether to skip a whole "word" (insets with
505         /// the same mathclass)
506         bool mathForward(bool word);
507         ///
508         bool mathBackward(bool word);
509         ///
510         void plainErase();
511         ///
512         void plainInsert(MathAtom const & at);
513
514         /// interpret name of a macro or ditch it if \c cancel is true.
515         /// Returns true if something got inserted.
516         bool macroModeClose(bool cancel = false);
517         /// are we currently typing the name of a macro?
518         bool inMacroMode() const;
519         /// get access to the macro we are currently typing
520         InsetMathUnknown * activeMacro();
521         /// get access to the macro we are currently typing
522         InsetMathUnknown const * activeMacro() const;
523         /// the name of the macro we are currently inputting
524         docstring macroName();
525
526         /// replace selected stuff with at, placing the former
527         // selection in entry cell of atom
528         void handleNest(MathAtom const & at);
529
530         /// make sure cursor position is valid
531         /// FIXME: It does a subset of fixIfBroken. Maybe merge them?
532         void normalize();
533
534         /// injects content of a cell into parent
535         void pullArg();
536         /// split font inset etc
537         void handleFont(std::string const & font);
538
539         /// can we enter the inset?
540         bool openable(MathAtom const &) const;
541         /// font at cursor position
542         Font getFont() const;
543 };
544
545
546 /**
547  * Notifies all insets which appear in \c old, but not in \c cur. And then
548  * notify all insets which appear in \c cur, but not in \c old.
549  * \returns true if cursor is now invalid, e.g. if some insets in
550  *   higher cursor slices of \c old do not exist anymore. In this case
551  *   it may be necessary to use Use Cursor::fixIfBroken.
552  */
553 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur);
554
555
556 } // namespace lyx
557
558 #endif // LCURSOR_H