]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
* GuiPrefs: fix typo.
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "ErrorList.h"
32 #include "factory.h"
33 #include "FuncRequest.h"
34 #include "InsetList.h"
35 #include "Intl.h"
36 #include "Language.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "LyXFunc.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Application.h"
50 #include "frontends/Clipboard.h"
51 #include "frontends/LyXView.h"
52 #include "frontends/Selection.h"
53 #include "frontends/WorkArea.h"
54
55 #include "insets/InsetCollapsable.h"
56 #include "insets/InsetCommand.h"
57 #include "insets/InsetExternal.h"
58 #include "insets/InsetFloatList.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetGraphicsParams.h"
61 #include "insets/InsetNewline.h"
62 #include "insets/InsetQuotes.h"
63 #include "insets/InsetSpecialChar.h"
64 #include "insets/InsetText.h"
65
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/gettext.h"
69 #include "support/lstrings.h"
70 #include "support/lyxtime.h"
71 #include "support/os.h"
72
73 #include "mathed/InsetMathHull.h"
74 #include "mathed/MathMacroTemplate.h"
75
76 #include <boost/next_prior.hpp>
77
78 #include <clocale>
79 #include <sstream>
80
81 using namespace std;
82 using namespace lyx::support;
83
84 namespace lyx {
85
86 using cap::copySelection;
87 using cap::cutSelection;
88 using cap::pasteFromStack;
89 using cap::pasteClipboardText;
90 using cap::pasteClipboardGraphics;
91 using cap::replaceSelection;
92 using cap::grabAndEraseSelection;
93 using cap::selClearOrDel;
94
95 // globals...
96 static Font freefont(ignore_font, ignore_language);
97 static bool toggleall = false;
98
99 static void toggleAndShow(Cursor & cur, Text * text,
100         Font const & font, bool toggleall = true)
101 {
102         text->toggleFree(cur, font, toggleall);
103
104         if (font.language() != ignore_language ||
105             font.fontInfo().number() != FONT_IGNORE) {
106                 TextMetrics const & tm = cur.bv().textMetrics(text);
107                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
108                                                        cur.real_current_font))
109                         text->setCursor(cur, cur.pit(), cur.pos(),
110                                         false, !cur.boundary());
111         }
112 }
113
114
115 static void moveCursor(Cursor & cur, bool selecting)
116 {
117         if (selecting || cur.mark())
118                 cur.setSelection();
119 }
120
121
122 static void finishChange(Cursor & cur, bool selecting)
123 {
124         cur.finishUndo();
125         moveCursor(cur, selecting);
126 }
127
128
129 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
130 {
131         cur.recordUndo();
132         docstring sel = cur.selectionAsString(false);
133
134         // It may happen that sel is empty but there is a selection
135         replaceSelection(cur);
136
137         // Is this a valid formula?
138         bool valid = true;
139
140         if (sel.empty()) {
141 #ifdef ENABLE_ASSERTIONS
142                 const int old_pos = cur.pos();
143 #endif
144                 cur.insert(new InsetMathHull(hullSimple));
145 #ifdef ENABLE_ASSERTIONS
146                 LASSERT(old_pos == cur.pos(), /**/);
147 #endif
148                 cur.nextInset()->edit(cur, true);
149                 // don't do that also for LFUN_MATH_MODE
150                 // unless you want end up with always changing
151                 // to mathrm when opening an inlined inset --
152                 // I really hate "LyXfunc overloading"...
153                 if (display)
154                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
155                 // Avoid an unnecessary undo step if cmd.argument
156                 // is empty
157                 if (!cmd.argument().empty())
158                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
159                                                  cmd.argument()));
160         } else {
161                 // create a macro if we see "\\newcommand"
162                 // somewhere, and an ordinary formula
163                 // otherwise
164                 if (sel.find(from_ascii("\\newcommand")) == string::npos
165                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
166                                 && sel.find(from_ascii("\\def")) == string::npos)
167                 {
168                         InsetMathHull * formula = new InsetMathHull;
169                         string const selstr = to_utf8(sel);
170                         istringstream is(selstr);
171                         Lexer lex;
172                         lex.setStream(is);
173                         if (!formula->readQuiet(lex)) {
174                                 // No valid formula, let's try with delims
175                                 is.str("$" + selstr + "$");
176                                 lex.setStream(is);
177                                 if (!formula->readQuiet(lex)) {
178                                         // Still not valid, leave it as is
179                                         valid = false;
180                                         delete formula;
181                                         cur.insert(sel);
182                                 } else
183                                         cur.insert(formula);
184                         } else
185                                 cur.insert(formula);
186                 } else {
187                         cur.insert(new MathMacroTemplate(sel));
188                 }
189         }
190         if (valid)
191                 cur.message(from_utf8(N_("Math editor mode")));
192         else
193                 cur.message(from_utf8(N_("No valid math formula")));
194 }
195
196
197 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
198 {
199         BOOST_ASSERT(cmd.action == LFUN_REGEXP_MODE);
200         if (cur.inRegexped()) {
201                 cur.message(_("Already in regexp mode"));
202                 return;
203         }
204         cur.recordUndo();
205         docstring const save_selection = grabAndEraseSelection(cur);
206         selClearOrDel(cur);
207         // replaceSelection(cur);
208
209         cur.insert(new InsetMathHull(hullRegexp));
210         cur.nextInset()->edit(cur, true);
211         cur.niceInsert(save_selection);
212
213         cur.message(_("Regexp editor mode"));
214 }
215
216
217 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
218 {
219         cur.recordUndo();
220         cap::replaceSelection(cur);
221         cur.insert(new InsetSpecialChar(kind));
222         cur.posForward();
223 }
224
225
226 static bool doInsertInset(Cursor & cur, Text * text,
227         FuncRequest const & cmd, bool edit, bool pastesel)
228 {
229         Buffer & buffer = cur.bv().buffer();
230         BufferParams const & bparams = buffer.params();
231         Inset * inset = createInset(buffer, cmd);
232         if (!inset)
233                 return false;
234
235         if (InsetCollapsable * ci = inset->asInsetCollapsable())
236                 ci->setLayout(bparams);
237
238         cur.recordUndo();
239         if (cmd.action == LFUN_INDEX_INSERT) {
240                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
241                 text->insertInset(cur, inset);
242                 if (edit)
243                         inset->edit(cur, true);
244                 // Now put this into inset
245                 static_cast<InsetCollapsable *>(inset)->
246                                 text().insertStringAsParagraphs(cur, ds);
247                 return true;
248         }
249
250         bool gotsel = false;
251         if (cur.selection()) {
252                 cutSelection(cur, false, pastesel);
253                 cur.clearSelection();
254                 gotsel = true;
255         }
256         text->insertInset(cur, inset);
257
258         if (edit)
259                 inset->edit(cur, true);
260
261         if (!gotsel || !pastesel)
262                 return true;
263
264         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
265         cur.buffer()->errors("Paste");
266         cur.clearSelection(); // bug 393
267         cur.finishUndo();
268         InsetText * insetText = dynamic_cast<InsetText *>(inset);
269         if (insetText && (!insetText->allowMultiPar() || cur.lastpit() == 0)) {
270                 // reset first par to default
271                 cur.text()->paragraphs().begin()
272                         ->setPlainOrDefaultLayout(bparams.documentClass());
273                 cur.pos() = 0;
274                 cur.pit() = 0;
275                 // Merge multiple paragraphs -- hack
276                 while (cur.lastpit() > 0)
277                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
278                 cur.leaveInset(*inset);
279         } else {
280                 cur.leaveInset(*inset);
281                 // reset surrounding par to default
282                 DocumentClass const & dc = bparams.documentClass();
283                 docstring const layoutname = inset->usePlainLayout()
284                         ? dc.plainLayoutName()
285                         : dc.defaultLayoutName();
286                 text->setLayout(cur, layoutname);
287         }
288
289         return true;
290 }
291
292
293 string const freefont2string()
294 {
295         return freefont.toString(toggleall);
296 }
297
298
299 /// the type of outline operation
300 enum OutlineOp {
301         OutlineUp, // Move this header with text down
302         OutlineDown,   // Move this header with text up
303         OutlineIn, // Make this header deeper
304         OutlineOut // Make this header shallower
305 };
306
307
308 static void outline(OutlineOp mode, Cursor & cur)
309 {
310         Buffer & buf = *cur.buffer();
311         pit_type & pit = cur.pit();
312         ParagraphList & pars = buf.text().paragraphs();
313         ParagraphList::iterator bgn = pars.begin();
314         // The first paragraph of the area to be copied:
315         ParagraphList::iterator start = boost::next(bgn, pit);
316         // The final paragraph of area to be copied:
317         ParagraphList::iterator finish = start;
318         ParagraphList::iterator end = pars.end();
319
320         DocumentClass const & tc = buf.params().documentClass();
321
322         int const thistoclevel = start->layout().toclevel;
323         int toclevel;
324
325         // Move out (down) from this section header
326         if (finish != end)
327                 ++finish;
328         // Seek the one (on same level) below
329         for (; finish != end; ++finish) {
330                 toclevel = finish->layout().toclevel;
331                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel) {
332                         break;
333                 }
334         }
335
336         switch (mode) {
337                 case OutlineUp: {
338                         if (start == pars.begin())
339                                 // Nothing to move.
340                                 return;
341                         ParagraphList::iterator dest = start;
342                         // Move out (up) from this header
343                         if (dest == bgn)
344                                 return;
345                         // Search previous same-level header above
346                         do {
347                                 --dest;
348                                 toclevel = dest->layout().toclevel;
349                         } while(dest != bgn
350                                 && (toclevel == Layout::NOT_IN_TOC
351                                     || toclevel > thistoclevel));
352                         // Not found; do nothing
353                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
354                                 return;
355                         pit_type const newpit = distance(bgn, dest);
356                         pit_type const len = distance(start, finish);
357                         pit_type const deletepit = pit + len;
358                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
359                         pars.insert(dest, start, finish);
360                         start = boost::next(pars.begin(), deletepit);
361                         pit = newpit;
362                         pars.erase(start, finish);
363                         return;
364                 }
365                 case OutlineDown: {
366                         if (finish == end)
367                                 // Nothing to move.
368                                 return;
369                         // Go one down from *this* header:
370                         ParagraphList::iterator dest = boost::next(finish, 1);
371                         // Go further down to find header to insert in front of:
372                         for (; dest != end; ++dest) {
373                                 toclevel = dest->layout().toclevel;
374                                 if (toclevel != Layout::NOT_IN_TOC
375                                     && toclevel <= thistoclevel) {
376                                         break;
377                                 }
378                         }
379                         // One such was found:
380                         pit_type newpit = distance(bgn, dest);
381                         pit_type const len = distance(start, finish);
382                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
383                         pars.insert(dest, start, finish);
384                         start = boost::next(bgn, pit);
385                         pit = newpit - len;
386                         pars.erase(start, finish);
387                         return;
388                 }
389                 case OutlineIn: {
390                         pit_type const len = distance(start, finish);
391                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
392                         for (; start != finish; ++start) {
393                                 toclevel = start->layout().toclevel;
394                                 if (toclevel == Layout::NOT_IN_TOC)
395                                         continue;
396                                 DocumentClass::const_iterator lit = tc.begin();
397                                 DocumentClass::const_iterator len = tc.end();
398                                 for (; lit != len; ++lit) {
399                                         if (lit->toclevel == toclevel + 1 &&
400                                             start->layout().labeltype == lit->labeltype) {
401                                                 start->setLayout(*lit);
402                                                 break;
403                                         }
404                                 }
405                         }
406                         return;
407                 }
408                 case OutlineOut: {
409                         pit_type const len = distance(start, finish);
410                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
411                         for (; start != finish; ++start) {
412                                 toclevel = start->layout().toclevel;
413                                 if (toclevel == Layout::NOT_IN_TOC)
414                                         continue;
415                                 DocumentClass::const_iterator lit = tc.begin();
416                                 DocumentClass::const_iterator len = tc.end();
417                                 for (; lit != len; ++lit) {
418                                         if (lit->toclevel == toclevel - 1 &&
419                                                 start->layout().labeltype == lit->labeltype) {
420                                                         start->setLayout(*lit);
421                                                         break;
422                                         }
423                                 }
424                         }
425                         return;
426                 }
427         }
428 }
429
430
431 void Text::number(Cursor & cur)
432 {
433         FontInfo font = ignore_font;
434         font.setNumber(FONT_TOGGLE);
435         toggleAndShow(cur, this, Font(font, ignore_language));
436 }
437
438
439 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
440 {
441         return par.isRTL(buffer.params());
442 }
443
444
445 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
446 {
447         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
448
449         BufferView * bv = &cur.bv();
450         TextMetrics & tm = bv->textMetrics(this);
451         if (!tm.contains(cur.pit())) {
452                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
453                 tm = bv->textMetrics(this);
454         }
455
456         // FIXME: We use the update flag to indicates wether a singlePar or a
457         // full screen update is needed. We reset it here but shall we restore it
458         // at the end?
459         cur.noUpdate();
460
461         LASSERT(cur.text() == this, /**/);
462         CursorSlice oldTopSlice = cur.top();
463         bool oldBoundary = cur.boundary();
464         bool sel = cur.selection();
465         // Signals that, even if needsUpdate == false, an update of the
466         // cursor paragraph is required
467         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
468                 LyXAction::SingleParUpdate);
469         // Signals that a full-screen update is required
470         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
471                 LyXAction::NoUpdate) || singleParUpdate);
472
473         switch (cmd.action) {
474
475         case LFUN_PARAGRAPH_MOVE_DOWN: {
476                 pit_type const pit = cur.pit();
477                 recUndo(cur, pit, pit + 1);
478                 cur.finishUndo();
479                 swap(pars_[pit], pars_[pit + 1]);
480                 cur.buffer()->updateLabels();
481                 needsUpdate = true;
482                 ++cur.pit();
483                 break;
484         }
485
486         case LFUN_PARAGRAPH_MOVE_UP: {
487                 pit_type const pit = cur.pit();
488                 recUndo(cur, pit - 1, pit);
489                 cur.finishUndo();
490                 swap(pars_[pit], pars_[pit - 1]);
491                 cur.buffer()->updateLabels();
492                 --cur.pit();
493                 needsUpdate = true;
494                 break;
495         }
496
497         case LFUN_APPENDIX: {
498                 Paragraph & par = cur.paragraph();
499                 bool start = !par.params().startOfAppendix();
500
501 // FIXME: The code below only makes sense at top level.
502 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
503                 // ensure that we have only one start_of_appendix in this document
504                 // FIXME: this don't work for multipart document!
505                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
506                         if (pars_[tmp].params().startOfAppendix()) {
507                                 recUndo(cur, tmp);
508                                 pars_[tmp].params().startOfAppendix(false);
509                                 break;
510                         }
511                 }
512
513                 cur.recordUndo();
514                 par.params().startOfAppendix(start);
515
516                 // we can set the refreshing parameters now
517                 cur.buffer()->updateLabels();
518                 break;
519         }
520
521         case LFUN_WORD_DELETE_FORWARD:
522                 if (cur.selection())
523                         cutSelection(cur, true, false);
524                 else
525                         deleteWordForward(cur);
526                 finishChange(cur, false);
527                 break;
528
529         case LFUN_WORD_DELETE_BACKWARD:
530                 if (cur.selection())
531                         cutSelection(cur, true, false);
532                 else
533                         deleteWordBackward(cur);
534                 finishChange(cur, false);
535                 break;
536
537         case LFUN_LINE_DELETE:
538                 if (cur.selection())
539                         cutSelection(cur, true, false);
540                 else
541                         tm.deleteLineForward(cur);
542                 finishChange(cur, false);
543                 break;
544
545         case LFUN_BUFFER_BEGIN:
546         case LFUN_BUFFER_BEGIN_SELECT:
547                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
548                 if (cur.depth() == 1)
549                         needsUpdate |= cursorTop(cur);
550                 else
551                         cur.undispatched();
552                 cur.updateFlags(Update::FitCursor);
553                 break;
554
555         case LFUN_BUFFER_END:
556         case LFUN_BUFFER_END_SELECT:
557                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
558                 if (cur.depth() == 1)
559                         needsUpdate |= cursorBottom(cur);
560                 else
561                         cur.undispatched();
562                 cur.updateFlags(Update::FitCursor);
563                 break;
564
565         case LFUN_INSET_BEGIN:
566         case LFUN_INSET_BEGIN_SELECT:
567                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_BEGIN_SELECT);
568                 if (cur.depth() == 1 || cur.pos() > 0)
569                         needsUpdate |= cursorTop(cur);
570                 else
571                         cur.undispatched();
572                 cur.updateFlags(Update::FitCursor);
573                 break;
574
575         case LFUN_INSET_END:
576         case LFUN_INSET_END_SELECT:
577                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_END_SELECT);
578                 if (cur.depth() == 1 || cur.pos() < cur.lastpos())
579                         needsUpdate |= cursorBottom(cur);
580                 else
581                         cur.undispatched();
582                 cur.updateFlags(Update::FitCursor);
583                 break;
584
585         case LFUN_CHAR_FORWARD:
586         case LFUN_CHAR_FORWARD_SELECT:
587                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
588                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
589                 needsUpdate |= cursorForward(cur);
590
591                 if (!needsUpdate && oldTopSlice == cur.top()
592                                 && cur.boundary() == oldBoundary) {
593                         cur.undispatched();
594                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
595                 }
596                 break;
597
598         case LFUN_CHAR_BACKWARD:
599         case LFUN_CHAR_BACKWARD_SELECT:
600                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
601                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
602                 needsUpdate |= cursorBackward(cur);
603
604                 if (!needsUpdate && oldTopSlice == cur.top()
605                         && cur.boundary() == oldBoundary) {
606                         cur.undispatched();
607                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
608                 }
609                 break;
610
611         case LFUN_CHAR_LEFT:
612         case LFUN_CHAR_LEFT_SELECT:
613                 if (lyxrc.visual_cursor) {
614                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
615                         needsUpdate |= cursorVisLeft(cur);
616                         if (!needsUpdate && oldTopSlice == cur.top()
617                                         && cur.boundary() == oldBoundary) {
618                                 cur.undispatched();
619                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
620                         }
621                 } else {
622                         if (reverseDirectionNeeded(cur)) {
623                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
624                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
625                         } else {
626                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
627                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
628                         }
629                         dispatch(cur, cmd);
630                         return;
631                 }
632                 break;
633
634         case LFUN_CHAR_RIGHT:
635         case LFUN_CHAR_RIGHT_SELECT:
636                 if (lyxrc.visual_cursor) {
637                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
638                         needsUpdate |= cursorVisRight(cur);
639                         if (!needsUpdate && oldTopSlice == cur.top()
640                                         && cur.boundary() == oldBoundary) {
641                                 cur.undispatched();
642                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
643                         }
644                 } else {
645                         if (reverseDirectionNeeded(cur)) {
646                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
647                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
648                         } else {
649                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
650                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
651                         }
652                         dispatch(cur, cmd);
653                         return;
654                 }
655                 break;
656
657
658         case LFUN_UP_SELECT:
659         case LFUN_DOWN_SELECT:
660         case LFUN_UP:
661         case LFUN_DOWN: {
662                 // stop/start the selection
663                 bool select = cmd.action == LFUN_DOWN_SELECT ||
664                         cmd.action == LFUN_UP_SELECT;
665
666                 // move cursor up/down
667                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
668                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
669
670                 if (!atFirstOrLastRow) {
671                         needsUpdate |= cur.selHandle(select);   
672                         cur.selHandle(select);
673                         cur.upDownInText(up, needsUpdate);
674                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
675                 } else {
676                         // if the cursor cannot be moved up or down do not remove
677                         // the selection right now, but wait for the next dispatch.
678                         if (select)
679                                 needsUpdate |= cur.selHandle(select);   
680                         cur.upDownInText(up, needsUpdate);
681                         cur.undispatched();
682                 }
683
684                 break;
685         }
686
687         case LFUN_PARAGRAPH_UP:
688         case LFUN_PARAGRAPH_UP_SELECT:
689                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
690                 needsUpdate |= cursorUpParagraph(cur);
691                 break;
692
693         case LFUN_PARAGRAPH_DOWN:
694         case LFUN_PARAGRAPH_DOWN_SELECT:
695                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
696                 needsUpdate |= cursorDownParagraph(cur);
697                 break;
698
699         case LFUN_LINE_BEGIN:
700         case LFUN_LINE_BEGIN_SELECT:
701                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
702                 needsUpdate |= tm.cursorHome(cur);
703                 break;
704
705         case LFUN_LINE_END:
706         case LFUN_LINE_END_SELECT:
707                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
708                 needsUpdate |= tm.cursorEnd(cur);
709                 break;
710
711         case LFUN_WORD_RIGHT:
712         case LFUN_WORD_RIGHT_SELECT:
713                 if (lyxrc.visual_cursor) {
714                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_RIGHT_SELECT);
715                         needsUpdate |= cursorVisRightOneWord(cur);
716                         if (!needsUpdate && oldTopSlice == cur.top()
717                                         && cur.boundary() == oldBoundary) {
718                                 cur.undispatched();
719                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
720                         }
721                 } else {
722                         if (reverseDirectionNeeded(cur)) {
723                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
724                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
725                         } else {
726                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
727                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
728                         }
729                         dispatch(cur, cmd);
730                         return;
731                 }
732                 break;
733
734         case LFUN_WORD_FORWARD:
735         case LFUN_WORD_FORWARD_SELECT:
736                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
737                 needsUpdate |= cursorForwardOneWord(cur);
738                 break;
739
740         case LFUN_WORD_LEFT:
741         case LFUN_WORD_LEFT_SELECT:
742                 if (lyxrc.visual_cursor) {
743                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_LEFT_SELECT);
744                         needsUpdate |= cursorVisLeftOneWord(cur);
745                         if (!needsUpdate && oldTopSlice == cur.top()
746                                         && cur.boundary() == oldBoundary) {
747                                 cur.undispatched();
748                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
749                         }
750                 } else {
751                         if (reverseDirectionNeeded(cur)) {
752                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
753                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
754                         } else {
755                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
756                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
757                         }
758                         dispatch(cur, cmd);
759                         return;
760                 }
761                 break;
762
763         case LFUN_WORD_BACKWARD:
764         case LFUN_WORD_BACKWARD_SELECT:
765                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
766                 needsUpdate |= cursorBackwardOneWord(cur);
767                 break;
768
769         case LFUN_WORD_SELECT: {
770                 selectWord(cur, WHOLE_WORD);
771                 finishChange(cur, true);
772                 break;
773         }
774
775         case LFUN_NEWLINE_INSERT: {
776                 InsetNewlineParams inp;
777                 docstring arg = cmd.argument();
778                 // this avoids a double undo
779                 // FIXME: should not be needed, ideally
780                 if (!cur.selection())
781                         cur.recordUndo();
782                 cap::replaceSelection(cur);
783                 if (arg == "linebreak")
784                         inp.kind = InsetNewlineParams::LINEBREAK;
785                 else
786                         inp.kind = InsetNewlineParams::NEWLINE;
787                 cur.insert(new InsetNewline(inp));
788                 cur.posForward();
789                 moveCursor(cur, false);
790                 break;
791         }
792
793         case LFUN_CHAR_DELETE_FORWARD:
794                 if (!cur.selection()) {
795                         if (cur.pos() == cur.paragraph().size())
796                                 // Par boundary, force full-screen update
797                                 singleParUpdate = false;
798                         needsUpdate |= erase(cur);
799                         cur.resetAnchor();
800                         // It is possible to make it a lot faster still
801                         // just comment out the line below...
802                 } else {
803                         cutSelection(cur, true, false);
804                         singleParUpdate = false;
805                 }
806                 moveCursor(cur, false);
807                 break;
808
809         case LFUN_CHAR_DELETE_BACKWARD:
810                 if (!cur.selection()) {
811                         if (bv->getIntl().getTransManager().backspace()) {
812                                 // Par boundary, full-screen update
813                                 if (cur.pos() == 0)
814                                         singleParUpdate = false;
815                                 needsUpdate |= backspace(cur);
816                                 cur.resetAnchor();
817                                 // It is possible to make it a lot faster still
818                                 // just comment out the line below...
819                         }
820                 } else {
821                         cutSelection(cur, true, false);
822                         singleParUpdate = false;
823                 }
824                 break;
825
826         case LFUN_BREAK_PARAGRAPH:
827                 cap::replaceSelection(cur);
828                 breakParagraph(cur, cmd.argument() == "inverse");
829                 cur.resetAnchor();
830                 break;
831
832         // TODO
833         // With the creation of LFUN_PARAGRAPH_PARAMS, this is now redundant,
834         // as its duties can be performed there. Should it be removed??
835         // FIXME For now, it can just dispatch LFUN_PARAGRAPH_PARAMS...
836         case LFUN_PARAGRAPH_SPACING: {
837                 Paragraph & par = cur.paragraph();
838                 Spacing::Space cur_spacing = par.params().spacing().getSpace();
839                 string cur_value = "1.0";
840                 if (cur_spacing == Spacing::Other)
841                         cur_value = par.params().spacing().getValueAsString();
842
843                 istringstream is(to_utf8(cmd.argument()));
844                 string tmp;
845                 is >> tmp;
846                 Spacing::Space new_spacing = cur_spacing;
847                 string new_value = cur_value;
848                 if (tmp.empty()) {
849                         lyxerr << "Missing argument to `paragraph-spacing'"
850                                << endl;
851                 } else if (tmp == "single") {
852                         new_spacing = Spacing::Single;
853                 } else if (tmp == "onehalf") {
854                         new_spacing = Spacing::Onehalf;
855                 } else if (tmp == "double") {
856                         new_spacing = Spacing::Double;
857                 } else if (tmp == "other") {
858                         new_spacing = Spacing::Other;
859                         string tmpval = "0.0";
860                         is >> tmpval;
861                         lyxerr << "new_value = " << tmpval << endl;
862                         if (tmpval != "0.0")
863                                 new_value = tmpval;
864                 } else if (tmp == "default") {
865                         new_spacing = Spacing::Default;
866                 } else {
867                         lyxerr << to_utf8(_("Unknown spacing argument: "))
868                                << to_utf8(cmd.argument()) << endl;
869                 }
870                 if (cur_spacing != new_spacing || cur_value != new_value)
871                         par.params().spacing(Spacing(new_spacing, new_value));
872                 break;
873         }
874
875         case LFUN_INSET_INSERT: {
876                 cur.recordUndo();
877
878                 // We have to avoid triggering InstantPreview loading
879                 // before inserting into the document. See bug #5626.
880                 bool loaded = bv->buffer().isFullyLoaded();
881                 bv->buffer().setFullyLoaded(false);
882                 Inset * inset = createInset(bv->buffer(), cmd);
883                 bv->buffer().setFullyLoaded(loaded);
884
885                 if (inset) {
886                         // FIXME (Abdel 01/02/2006):
887                         // What follows would be a partial fix for bug 2154:
888                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
889                         // This automatically put the label inset _after_ a
890                         // numbered section. It should be possible to extend the mechanism
891                         // to any kind of LateX environement.
892                         // The correct way to fix that bug would be at LateX generation.
893                         // I'll let the code here for reference as it could be used for some
894                         // other feature like "automatic labelling".
895                         /*
896                         Paragraph & par = pars_[cur.pit()];
897                         if (inset->lyxCode() == LABEL_CODE
898                                 && par.layout().labeltype == LABEL_COUNTER) {
899                                 // Go to the end of the paragraph
900                                 // Warning: Because of Change-Tracking, the last
901                                 // position is 'size()' and not 'size()-1':
902                                 cur.pos() = par.size();
903                                 // Insert a new paragraph
904                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
905                                 dispatch(cur, fr);
906                         }
907                         */
908                         if (cur.selection())
909                                 cutSelection(cur, true, false);
910                         cur.insert(inset);
911                         cur.posForward();
912
913                         // trigger InstantPreview now
914                         if (inset->lyxCode() == EXTERNAL_CODE) {
915                                 InsetExternal & ins =
916                                         static_cast<InsetExternal &>(*inset);
917                                 ins.updatePreview();
918                         }
919                 }
920
921                 break;
922         }
923
924         case LFUN_INSET_DISSOLVE: {
925                 // first, try if there's an inset at cursor
926                 // FIXME: this first part should be moved to
927                 // a LFUN_NEXT_INSET_DISSOLVE, or be called via
928                 // some generic "next-inset inset-dissolve"
929                 Inset * inset = cur.nextInset();
930                 if (inset && inset->isActive()) {
931                         Cursor tmpcur = cur;
932                         tmpcur.pushBackward(*inset);
933                         inset->dispatch(tmpcur, cmd);
934                         if (tmpcur.result().dispatched()) {
935                                 cur.dispatched();
936                                 break;
937                         }
938                 }
939                 // if it did not work, try the underlying inset
940                 if (dissolveInset(cur)) {
941                         needsUpdate = true;
942                         break;
943                 }
944                 // if it did not work, do nothing.
945                 break;
946         }
947
948         case LFUN_SET_GRAPHICS_GROUP: {
949                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
950                 if (!ins)
951                         break;
952
953                 cur.recordUndo();
954
955                 string id = to_utf8(cmd.argument());
956                 string grp = graphics::getGroupParams(bv->buffer(), id);
957                 InsetGraphicsParams tmp, inspar = ins->getParams();
958
959                 if (id.empty())
960                         inspar.groupId = to_utf8(cmd.argument());
961                 else {
962                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
963                         tmp.filename = inspar.filename;
964                         inspar = tmp;
965                 }
966
967                 ins->setParams(inspar);
968         }
969
970         case LFUN_SPACE_INSERT:
971                 if (cur.paragraph().layout().free_spacing)
972                         insertChar(cur, ' ');
973                 else {
974                         doInsertInset(cur, this, cmd, false, false);
975                         cur.posForward();
976                 }
977                 moveCursor(cur, false);
978                 break;
979
980         case LFUN_SPECIALCHAR_INSERT: {
981                 string const name = to_utf8(cmd.argument());
982                 if (name == "hyphenation")
983                         specialChar(cur, InsetSpecialChar::HYPHENATION);
984                 else if (name == "ligature-break")
985                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
986                 else if (name == "slash")
987                         specialChar(cur, InsetSpecialChar::SLASH);
988                 else if (name == "nobreakdash")
989                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
990                 else if (name == "dots")
991                         specialChar(cur, InsetSpecialChar::LDOTS);
992                 else if (name == "end-of-sentence")
993                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
994                 else if (name == "menu-separator")
995                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
996                 else if (name.empty())
997                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
998                 else
999                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1000                 break;
1001         }
1002
1003         case LFUN_WORD_UPCASE:
1004                 changeCase(cur, text_uppercase);
1005                 break;
1006
1007         case LFUN_WORD_LOWCASE:
1008                 changeCase(cur, text_lowercase);
1009                 break;
1010
1011         case LFUN_WORD_CAPITALIZE:
1012                 changeCase(cur, text_capitalization);
1013                 break;
1014
1015         case LFUN_CHARS_TRANSPOSE:
1016                 charsTranspose(cur);
1017                 break;
1018
1019         case LFUN_PASTE: {
1020                 cur.message(_("Paste"));
1021                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1022                 cap::replaceSelection(cur);
1023
1024                 // without argument?
1025                 string const arg = to_utf8(cmd.argument());
1026                 if (arg.empty()) {
1027                         if (theClipboard().isInternal())
1028                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1029                         else if (theClipboard().hasGraphicsContents() 
1030                                      && !theClipboard().hasTextContents())
1031                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1032                         else
1033                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1034                 } else if (isStrUnsignedInt(arg)) {
1035                         // we have a numerical argument
1036                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1037                                        convert<unsigned int>(arg));
1038                 } else {
1039                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1040                         if (arg == "pdf")
1041                                 type = Clipboard::PdfGraphicsType;
1042                         else if (arg == "png")
1043                                 type = Clipboard::PngGraphicsType;
1044                         else if (arg == "jpeg")
1045                                 type = Clipboard::JpegGraphicsType;
1046                         else if (arg == "linkback")
1047                                 type = Clipboard::LinkBackGraphicsType;
1048                         else
1049                                 LASSERT(false, /**/);
1050
1051                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1052                 }
1053
1054                 bv->buffer().errors("Paste");
1055                 cur.clearSelection(); // bug 393
1056                 cur.finishUndo();
1057                 break;
1058         }
1059
1060         case LFUN_CUT:
1061                 cutSelection(cur, true, true);
1062                 cur.message(_("Cut"));
1063                 break;
1064
1065         case LFUN_COPY:
1066                 copySelection(cur);
1067                 cur.message(_("Copy"));
1068                 break;
1069
1070         case LFUN_SERVER_GET_XY:
1071                 cur.message(from_utf8(
1072                         convert<string>(tm.cursorX(cur.top(), cur.boundary()))
1073                         + ' ' + convert<string>(tm.cursorY(cur.top(), cur.boundary()))));
1074                 break;
1075
1076         case LFUN_SERVER_SET_XY: {
1077                 int x = 0;
1078                 int y = 0;
1079                 istringstream is(to_utf8(cmd.argument()));
1080                 is >> x >> y;
1081                 if (!is)
1082                         lyxerr << "SETXY: Could not parse coordinates in '"
1083                                << to_utf8(cmd.argument()) << endl;
1084                 else
1085                         tm.setCursorFromCoordinates(cur, x, y);
1086                 break;
1087         }
1088
1089         case LFUN_SERVER_GET_LAYOUT:
1090                 cur.message(cur.paragraph().layout().name());
1091                 break;
1092
1093         case LFUN_LAYOUT: {
1094                 docstring layout = cmd.argument();
1095                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1096
1097                 Paragraph const & para = cur.paragraph();
1098                 docstring const old_layout = para.layout().name();
1099                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1100
1101                 if (layout.empty())
1102                         layout = tclass.defaultLayoutName();
1103
1104                 if (para.forcePlainLayout())
1105                         // in this case only the empty layout is allowed
1106                         layout = tclass.plainLayoutName();
1107                 else if (para.usePlainLayout()) {
1108                         // in this case, default layout maps to empty layout
1109                         if (layout == tclass.defaultLayoutName())
1110                                 layout = tclass.plainLayoutName();
1111                 } else {
1112                         // otherwise, the empty layout maps to the default
1113                         if (layout == tclass.plainLayoutName())
1114                                 layout = tclass.defaultLayoutName();
1115                 }
1116
1117                 bool hasLayout = tclass.hasLayout(layout);
1118
1119                 // If the entry is obsolete, use the new one instead.
1120                 if (hasLayout) {
1121                         docstring const & obs = tclass[layout].obsoleted_by();
1122                         if (!obs.empty())
1123                                 layout = obs;
1124                 }
1125
1126                 if (!hasLayout) {
1127                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1128                                 from_utf8(N_(" not known")));
1129                         break;
1130                 }
1131
1132                 bool change_layout = (old_layout != layout);
1133
1134                 if (!change_layout && cur.selection() &&
1135                         cur.selBegin().pit() != cur.selEnd().pit())
1136                 {
1137                         pit_type spit = cur.selBegin().pit();
1138                         pit_type epit = cur.selEnd().pit() + 1;
1139                         while (spit != epit) {
1140                                 if (pars_[spit].layout().name() != old_layout) {
1141                                         change_layout = true;
1142                                         break;
1143                                 }
1144                                 ++spit;
1145                         }
1146                 }
1147
1148                 if (change_layout)
1149                         setLayout(cur, layout);
1150
1151                 break;
1152         }
1153
1154         case LFUN_CLIPBOARD_PASTE:
1155                 cur.clearSelection();
1156                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1157                                cmd.argument() == "paragraph");
1158                 bv->buffer().errors("Paste");
1159                 break;
1160
1161         case LFUN_PRIMARY_SELECTION_PASTE:
1162                 pasteString(cur, theSelection().get(),
1163                             cmd.argument() == "paragraph");
1164                 break;
1165
1166         case LFUN_SELECTION_PASTE:
1167                 // Copy the selection buffer to the clipboard stack,
1168                 // because we want it to appear in the "Edit->Paste
1169                 // recent" menu.
1170                 cap::copySelectionToStack();
1171                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1172                 bv->buffer().errors("Paste");
1173                 break;
1174
1175         case LFUN_UNICODE_INSERT: {
1176                 if (cmd.argument().empty())
1177                         break;
1178                 docstring hexstring = cmd.argument();
1179                 if (isHex(hexstring)) {
1180                         char_type c = hexToInt(hexstring);
1181                         if (c >= 32 && c < 0x10ffff) {
1182                                 lyxerr << "Inserting c: " << c << endl;
1183                                 docstring s = docstring(1, c);
1184                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1185                         }
1186                 }
1187                 break;
1188         }
1189
1190         case LFUN_QUOTE_INSERT: {
1191                 Paragraph & par = cur.paragraph();
1192                 pos_type pos = cur.pos();
1193                 BufferParams const & bufparams = bv->buffer().params();
1194                 Layout const & style = par.layout();
1195                 InsetLayout const & ilayout = cur.inset().getLayout(bufparams);
1196                 if (!style.pass_thru && !ilayout.isPassThru()
1197                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1198                         // this avoids a double undo
1199                         // FIXME: should not be needed, ideally
1200                         if (!cur.selection())
1201                                 cur.recordUndo();
1202                         cap::replaceSelection(cur);
1203                         pos = cur.pos();
1204                         char_type c;
1205                         if (pos == 0)
1206                                 c = ' ';
1207                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1208                                 c = ' ';
1209                         else
1210                                 c = par.getChar(pos - 1);
1211                         string arg = to_utf8(cmd.argument());
1212                         cur.insert(new InsetQuotes(bv->buffer(), c, (arg == "single")
1213                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1214                         cur.posForward();
1215                 }
1216                 else
1217                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1218                 break;
1219         }
1220
1221         case LFUN_DATE_INSERT: {
1222                 string const format = cmd.argument().empty()
1223                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1224                 string const time = formatted_time(current_time(), format);
1225                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1226                 break;
1227         }
1228
1229         case LFUN_MOUSE_TRIPLE:
1230                 if (cmd.button() == mouse_button::button1) {
1231                         tm.cursorHome(cur);
1232                         cur.resetAnchor();
1233                         tm.cursorEnd(cur);
1234                         cur.setSelection();
1235                         bv->cursor() = cur;
1236                 }
1237                 break;
1238
1239         case LFUN_MOUSE_DOUBLE:
1240                 if (cmd.button() == mouse_button::button1) {
1241                         selectWord(cur, WHOLE_WORD_STRICT);
1242                         bv->cursor() = cur;
1243                 }
1244                 break;
1245
1246         // Single-click on work area
1247         case LFUN_MOUSE_PRESS:
1248                 // We are not marking a selection with the keyboard in any case.
1249                 cur.bv().cursor().setMark(false);
1250                 switch (cmd.button()) {
1251                 case mouse_button::button1:
1252                         // Set the cursor
1253                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1254                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1255                         break;
1256
1257                 case mouse_button::button2:
1258                         // Middle mouse pasting.
1259                         bv->mouseSetCursor(cur);
1260                         lyx::dispatch(
1261                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1262                                             "selection-paste ; primary-selection-paste paragraph"));
1263                         cur.noUpdate();
1264                         break;
1265
1266                 case mouse_button::button3: {
1267                         Cursor const & bvcur = cur.bv().cursor();
1268                         // Don't do anything if we right-click a
1269                         // selection, a context menu will popup.
1270                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1271                             && cur < bvcur.selectionEnd()) {
1272                                 cur.noUpdate();
1273                                 return;
1274                         }
1275                         if (!bv->mouseSetCursor(cur, false))
1276                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1277                         break;
1278                 }
1279
1280                 default:
1281                         break;
1282                 } // switch (cmd.button())
1283                 break;
1284
1285         case LFUN_MOUSE_MOTION: {
1286                 // Mouse motion with right or middle mouse do nothing for now.
1287                 if (cmd.button() != mouse_button::button1) {
1288                         cur.noUpdate();
1289                         return;
1290                 }
1291                 // ignore motions deeper nested than the real anchor
1292                 Cursor & bvcur = cur.bv().cursor();
1293                 if (!bvcur.anchor_.hasPart(cur)) {
1294                         cur.undispatched();
1295                         break;
1296                 }
1297                 CursorSlice old = bvcur.top();
1298
1299                 int const wh = bv->workHeight();
1300                 int const y = max(0, min(wh - 1, cmd.y));
1301
1302                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1303                 cur.setTargetX(cmd.x);
1304                 if (cmd.y >= wh)
1305                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1306                 else if (cmd.y < 0)
1307                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1308                 // This is to allow jumping over large insets
1309                 if (cur.top() == old) {
1310                         if (cmd.y >= wh)
1311                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1312                         else if (cmd.y < 0)
1313                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1314                 }
1315                 // We continue with our existing selection or start a new one, so don't
1316                 // reset the anchor.
1317                 bvcur.setCursor(cur);
1318                 bvcur.setSelection(true);
1319                 if (cur.top() == old) {
1320                         // We didn't move one iota, so no need to update the screen.
1321                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1322                         //cur.noUpdate();
1323                         return;
1324                 }
1325                 break;
1326         }
1327
1328         case LFUN_MOUSE_RELEASE:
1329                 switch (cmd.button()) {
1330                 case mouse_button::button1:
1331                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1332                         // If there is a new selection, update persistent selection;
1333                         // otherwise, single click does not clear persistent selection
1334                         // buffer.
1335                         if (cur.selection()) {
1336                                 // Finish selection. If double click,
1337                                 // cur is moved to the end of word by
1338                                 // selectWord but bvcur is current
1339                                 // mouse position.
1340                                 cur.bv().cursor().setSelection();
1341                                 // We might have removed an empty but drawn selection
1342                                 // (probably a margin)
1343                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1344                         } else
1345                                 cur.noUpdate();
1346                         // FIXME: We could try to handle drag and drop of selection here.
1347                         return;
1348
1349                 case mouse_button::button2:
1350                         // Middle mouse pasting is handled at mouse press time,
1351                         // see LFUN_MOUSE_PRESS.
1352                         cur.noUpdate();
1353                         return;
1354
1355                 case mouse_button::button3:
1356                         // Cursor was set at LFUN_MOUSE_PRESS time.
1357                         // FIXME: If there is a selection we could try to handle a special
1358                         // drag & drop context menu.
1359                         cur.noUpdate();
1360                         return;
1361
1362                 case mouse_button::none:
1363                 case mouse_button::button4:
1364                 case mouse_button::button5:
1365                         break;
1366                 } // switch (cmd.button())
1367
1368                 break;
1369
1370         case LFUN_SELF_INSERT: {
1371                 if (cmd.argument().empty())
1372                         break;
1373
1374                 // Automatically delete the currently selected
1375                 // text and replace it with what is being
1376                 // typed in now. Depends on lyxrc settings
1377                 // "auto_region_delete", which defaults to
1378                 // true (on).
1379
1380                 if (lyxrc.auto_region_delete && cur.selection())
1381                         cutSelection(cur, false, false);
1382
1383                 cur.clearSelection();
1384
1385                 docstring::const_iterator cit = cmd.argument().begin();
1386                 docstring::const_iterator const end = cmd.argument().end();
1387                 for (; cit != end; ++cit)
1388                         bv->translateAndInsert(*cit, this, cur);
1389
1390                 cur.resetAnchor();
1391                 moveCursor(cur, false);
1392                 bv->bookmarkEditPosition();
1393                 break;
1394         }
1395
1396         case LFUN_HYPERLINK_INSERT: {
1397                 InsetCommandParams p(HYPERLINK_CODE);
1398                 docstring content;
1399                 if (cur.selection()) {
1400                         content = cur.selectionAsString(false);
1401                         cutSelection(cur, true, false);
1402                 }
1403                 p["target"] = (cmd.argument().empty()) ?
1404                         content : cmd.argument();
1405                 string const data = InsetCommand::params2string("href", p);
1406                 if (p["target"].empty()) {
1407                         bv->showDialog("href", data);
1408                 } else {
1409                         FuncRequest fr(LFUN_INSET_INSERT, data);
1410                         dispatch(cur, fr);
1411                 }
1412                 break;
1413         }
1414
1415         case LFUN_LABEL_INSERT: {
1416                 InsetCommandParams p(LABEL_CODE);
1417                 // Try to generate a valid label
1418                 p["name"] = (cmd.argument().empty()) ?
1419                         cur.getPossibleLabel() :
1420                         cmd.argument();
1421                 string const data = InsetCommand::params2string("label", p);
1422
1423                 if (cmd.argument().empty()) {
1424                         bv->showDialog("label", data);
1425                 } else {
1426                         FuncRequest fr(LFUN_INSET_INSERT, data);
1427                         dispatch(cur, fr);
1428                 }
1429                 break;
1430         }
1431
1432         case LFUN_INFO_INSERT: {
1433                 Inset * inset;
1434                 if (cmd.argument().empty() && cur.selection()) {
1435                         // if command argument is empty use current selection as parameter.
1436                         docstring ds = cur.selectionAsString(false);
1437                         cutSelection(cur, true, false);
1438                         FuncRequest cmd0(cmd, ds);
1439                         inset = createInset(cur.bv().buffer(), cmd0);
1440                 } else {
1441                         inset = createInset(cur.bv().buffer(), cmd);
1442                 }
1443                 if (!inset)
1444                         break;
1445                 insertInset(cur, inset);
1446                 cur.posForward();
1447                 break;
1448         }
1449         case LFUN_CAPTION_INSERT:
1450         case LFUN_FOOTNOTE_INSERT:
1451         case LFUN_NOTE_INSERT:
1452         case LFUN_FLEX_INSERT:
1453         case LFUN_BOX_INSERT:
1454         case LFUN_BRANCH_INSERT:
1455         case LFUN_PHANTOM_INSERT:
1456         case LFUN_ERT_INSERT:
1457         case LFUN_LISTING_INSERT:
1458         case LFUN_MARGINALNOTE_INSERT:
1459         case LFUN_OPTIONAL_INSERT:
1460         case LFUN_INDEX_INSERT:
1461                 // Open the inset, and move the current selection
1462                 // inside it.
1463                 doInsertInset(cur, this, cmd, true, true);
1464                 cur.posForward();
1465                 // Some insets are numbered, others are shown in the outline pane so
1466                 // let's update the labels and the toc backend.
1467                 bv->buffer().updateLabels();
1468                 break;
1469
1470         case LFUN_TABULAR_INSERT:
1471                 // if there were no arguments, just open the dialog
1472                 if (doInsertInset(cur, this, cmd, false, true))
1473                         cur.posForward();
1474                 else
1475                         bv->showDialog("tabularcreate");
1476
1477                 break;
1478
1479         case LFUN_FLOAT_INSERT:
1480         case LFUN_FLOAT_WIDE_INSERT:
1481         case LFUN_WRAP_INSERT: {
1482                 // will some text be moved into the inset?
1483                 bool content = cur.selection();
1484
1485                 doInsertInset(cur, this, cmd, true, true);
1486                 cur.posForward();
1487
1488                 // If some text is moved into the inset, doInsertInset 
1489                 // puts the cursor outside the inset. To insert the
1490                 // caption we put it back into the inset.
1491                 if (content)
1492                         cur.backwardPos();
1493
1494                 ParagraphList & pars = cur.text()->paragraphs();
1495
1496                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1497
1498                 // add a separate paragraph for the caption inset
1499                 pars.push_back(Paragraph());
1500                 pars.back().setInsetOwner(&pars[0].inInset());
1501                 pars.back().setPlainOrDefaultLayout(tclass);
1502                 int cap_pit = pars.size() - 1;
1503
1504                 // if an empty inset was created, we create an additional empty
1505                 // paragraph at the bottom so that the user can choose where to put
1506                 // the graphics (or table).
1507                 if (!content) {
1508                         pars.push_back(Paragraph());
1509                         pars.back().setInsetOwner(&pars[0].inInset());
1510                         pars.back().setPlainOrDefaultLayout(tclass);
1511                 }
1512
1513                 // reposition the cursor to the caption
1514                 cur.pit() = cap_pit;
1515                 cur.pos() = 0;
1516                 // FIXME: This Text/Cursor dispatch handling is a mess!
1517                 // We cannot use Cursor::dispatch here it needs access to up to
1518                 // date metrics.
1519                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1520                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1521                 bv->buffer().updateLabels();
1522                 cur.updateFlags(Update::Force);
1523                 // FIXME: When leaving the Float (or Wrap) inset we should
1524                 // delete any empty paragraph left above or below the
1525                 // caption.
1526                 break;
1527         }
1528
1529         case LFUN_NOMENCL_INSERT: {
1530                 InsetCommandParams p(NOMENCL_CODE);
1531                 if (cmd.argument().empty())
1532                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1533                 else
1534                         p["symbol"] = cmd.argument();
1535                 string const data = InsetCommand::params2string("nomenclature", p);
1536                 bv->showDialog("nomenclature", data);
1537                 break;
1538         }
1539
1540         case LFUN_INDEX_PRINT:
1541         case LFUN_NOMENCL_PRINT:
1542         case LFUN_TOC_INSERT:
1543         case LFUN_LINE_INSERT:
1544         case LFUN_NEWPAGE_INSERT:
1545                 // do nothing fancy
1546                 doInsertInset(cur, this, cmd, false, false);
1547                 cur.posForward();
1548                 break;
1549
1550         case LFUN_DEPTH_DECREMENT:
1551                 changeDepth(cur, DEC_DEPTH);
1552                 break;
1553
1554         case LFUN_DEPTH_INCREMENT:
1555                 changeDepth(cur, INC_DEPTH);
1556                 break;
1557
1558         case LFUN_MATH_DISPLAY:
1559                 mathDispatch(cur, cmd, true);
1560                 break;
1561
1562         case LFUN_REGEXP_MODE:
1563                 regexpDispatch(cur, cmd);
1564                 break;
1565
1566         case LFUN_MATH_MODE:
1567                 if (cmd.argument() == "on")
1568                         // don't pass "on" as argument
1569                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1570                 else
1571                         mathDispatch(cur, cmd, false);
1572                 break;
1573
1574         case LFUN_MATH_MACRO:
1575                 if (cmd.argument().empty())
1576                         cur.errorMessage(from_utf8(N_("Missing argument")));
1577                 else {
1578                         string s = to_utf8(cmd.argument());
1579                         string const s1 = token(s, ' ', 1);
1580                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1581                         string const s2 = token(s, ' ', 2);
1582                         MacroType type = MacroTypeNewcommand;
1583                         if (s2 == "def")
1584                                 type = MacroTypeDef;
1585                         MathMacroTemplate * inset = new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type);
1586                         inset->setBuffer(bv->buffer());
1587                         insertInset(cur, inset);
1588
1589                         // enter macro inset and select the name
1590                         cur.push(*inset);
1591                         cur.top().pos() = cur.top().lastpos();
1592                         cur.resetAnchor();
1593                         cur.setSelection(true);
1594                         cur.top().pos() = 0;
1595                 }
1596                 break;
1597
1598         // passthrough hat and underscore outside mathed:
1599         case LFUN_MATH_SUBSCRIPT:
1600                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1601                 break;
1602         case LFUN_MATH_SUPERSCRIPT:
1603                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1604                 break;
1605
1606         case LFUN_MATH_INSERT:
1607         case LFUN_MATH_MATRIX:
1608         case LFUN_MATH_DELIM:
1609         case LFUN_MATH_BIGDELIM: {
1610                 cur.recordUndo();
1611                 cap::replaceSelection(cur);
1612                 cur.insert(new InsetMathHull(hullSimple));
1613                 checkAndActivateInset(cur, true);
1614                 LASSERT(cur.inMathed(), /**/);
1615                 cur.dispatch(cmd);
1616                 break;
1617         }
1618
1619         case LFUN_FONT_EMPH: {
1620                 Font font(ignore_font, ignore_language);
1621                 font.fontInfo().setEmph(FONT_TOGGLE);
1622                 toggleAndShow(cur, this, font);
1623                 break;
1624         }
1625
1626         case LFUN_FONT_ITAL: {
1627                 Font font(ignore_font, ignore_language);
1628                 font.fontInfo().setShape(ITALIC_SHAPE);
1629                 toggleAndShow(cur, this, font);
1630                 break;
1631         }
1632
1633         case LFUN_FONT_BOLD:
1634         case LFUN_FONT_BOLDSYMBOL: {
1635                 Font font(ignore_font, ignore_language);
1636                 font.fontInfo().setSeries(BOLD_SERIES);
1637                 toggleAndShow(cur, this, font);
1638                 break;
1639         }
1640
1641         case LFUN_FONT_NOUN: {
1642                 Font font(ignore_font, ignore_language);
1643                 font.fontInfo().setNoun(FONT_TOGGLE);
1644                 toggleAndShow(cur, this, font);
1645                 break;
1646         }
1647
1648         case LFUN_FONT_TYPEWRITER: {
1649                 Font font(ignore_font, ignore_language);
1650                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1651                 toggleAndShow(cur, this, font);
1652                 break;
1653         }
1654
1655         case LFUN_FONT_SANS: {
1656                 Font font(ignore_font, ignore_language);
1657                 font.fontInfo().setFamily(SANS_FAMILY);
1658                 toggleAndShow(cur, this, font);
1659                 break;
1660         }
1661
1662         case LFUN_FONT_ROMAN: {
1663                 Font font(ignore_font, ignore_language);
1664                 font.fontInfo().setFamily(ROMAN_FAMILY);
1665                 toggleAndShow(cur, this, font);
1666                 break;
1667         }
1668
1669         case LFUN_FONT_DEFAULT: {
1670                 Font font(inherit_font, ignore_language);
1671                 toggleAndShow(cur, this, font);
1672                 break;
1673         }
1674
1675         case LFUN_FONT_UNDERLINE: {
1676                 Font font(ignore_font, ignore_language);
1677                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1678                 toggleAndShow(cur, this, font);
1679                 break;
1680         }
1681
1682         case LFUN_FONT_SIZE: {
1683                 Font font(ignore_font, ignore_language);
1684                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1685                 toggleAndShow(cur, this, font);
1686                 break;
1687         }
1688
1689         case LFUN_LANGUAGE: {
1690                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1691                 if (!lang)
1692                         break;
1693                 Font font(ignore_font, lang);
1694                 toggleAndShow(cur, this, font);
1695                 break;
1696         }
1697
1698         case LFUN_TEXTSTYLE_APPLY:
1699                 toggleAndShow(cur, this, freefont, toggleall);
1700                 cur.message(_("Character set"));
1701                 break;
1702
1703         // Set the freefont using the contents of \param data dispatched from
1704         // the frontends and apply it at the current cursor location.
1705         case LFUN_TEXTSTYLE_UPDATE: {
1706                 Font font;
1707                 bool toggle;
1708                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1709                         freefont = font;
1710                         toggleall = toggle;
1711                         toggleAndShow(cur, this, freefont, toggleall);
1712                         cur.message(_("Character set"));
1713                 } else {
1714                         lyxerr << "Argument not ok";
1715                 }
1716                 break;
1717         }
1718
1719         case LFUN_FINISHED_LEFT:
1720                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1721                 // We're leaving an inset, going left. If the inset is LTR, we're
1722                 // leaving from the front, so we should not move (remain at --- but
1723                 // not in --- the inset). If the inset is RTL, move left, without
1724                 // entering the inset itself; i.e., move to after the inset.
1725                 if (cur.paragraph().getFontSettings(
1726                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1727                         cursorVisLeft(cur, true);
1728                 break;
1729
1730         case LFUN_FINISHED_RIGHT:
1731                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1732                 // We're leaving an inset, going right. If the inset is RTL, we're
1733                 // leaving from the front, so we should not move (remain at --- but
1734                 // not in --- the inset). If the inset is LTR, move right, without
1735                 // entering the inset itself; i.e., move to after the inset.
1736                 if (!cur.paragraph().getFontSettings(
1737                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1738                         cursorVisRight(cur, true);
1739                 break;
1740
1741         case LFUN_FINISHED_BACKWARD:
1742                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1743                 break;
1744
1745         case LFUN_FINISHED_FORWARD:
1746                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1747                 ++cur.pos();
1748                 cur.setCurrentFont();
1749                 break;
1750
1751         case LFUN_LAYOUT_PARAGRAPH: {
1752                 string data;
1753                 params2string(cur.paragraph(), data);
1754                 data = "show\n" + data;
1755                 bv->showDialog("paragraph", data);
1756                 break;
1757         }
1758
1759         case LFUN_PARAGRAPH_UPDATE: {
1760                 string data;
1761                 params2string(cur.paragraph(), data);
1762
1763                 // Will the paragraph accept changes from the dialog?
1764                 bool const accept =
1765                         cur.inset().allowParagraphCustomization(cur.idx());
1766
1767                 data = "update " + convert<string>(accept) + '\n' + data;
1768                 bv->updateDialog("paragraph", data);
1769                 break;
1770         }
1771
1772         case LFUN_ACCENT_UMLAUT:
1773         case LFUN_ACCENT_CIRCUMFLEX:
1774         case LFUN_ACCENT_GRAVE:
1775         case LFUN_ACCENT_ACUTE:
1776         case LFUN_ACCENT_TILDE:
1777         case LFUN_ACCENT_CEDILLA:
1778         case LFUN_ACCENT_MACRON:
1779         case LFUN_ACCENT_DOT:
1780         case LFUN_ACCENT_UNDERDOT:
1781         case LFUN_ACCENT_UNDERBAR:
1782         case LFUN_ACCENT_CARON:
1783         case LFUN_ACCENT_BREVE:
1784         case LFUN_ACCENT_TIE:
1785         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1786         case LFUN_ACCENT_CIRCLE:
1787         case LFUN_ACCENT_OGONEK:
1788                 theLyXFunc().handleKeyFunc(cmd.action);
1789                 if (!cmd.argument().empty())
1790                         // FIXME: Are all these characters encoded in one byte in utf8?
1791                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1792                 break;
1793
1794         case LFUN_FLOAT_LIST_INSERT: {
1795                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1796                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1797                         cur.recordUndo();
1798                         if (cur.selection())
1799                                 cutSelection(cur, true, false);
1800                         breakParagraph(cur);
1801
1802                         if (cur.lastpos() != 0) {
1803                                 cursorBackward(cur);
1804                                 breakParagraph(cur);
1805                         }
1806
1807                         docstring const laystr = cur.inset().usePlainLayout() ?
1808                                 tclass.plainLayoutName() :
1809                                 tclass.defaultLayoutName();
1810                         setLayout(cur, laystr);
1811                         ParagraphParameters p;
1812                         // FIXME If this call were replaced with one to clearParagraphParams(),
1813                         // then we could get rid of this method altogether.
1814                         setParagraphs(cur, p);
1815                         // FIXME This should be simplified when InsetFloatList takes a
1816                         // Buffer in its constructor.
1817                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
1818                         ifl->setBuffer(bv->buffer());
1819                         insertInset(cur, ifl);
1820                         cur.posForward();
1821                 } else {
1822                         lyxerr << "Non-existent float type: "
1823                                << to_utf8(cmd.argument()) << endl;
1824                 }
1825                 break;
1826         }
1827
1828         case LFUN_CHANGE_ACCEPT: {
1829                 acceptOrRejectChanges(cur, ACCEPT);
1830                 break;
1831         }
1832
1833         case LFUN_CHANGE_REJECT: {
1834                 acceptOrRejectChanges(cur, REJECT);
1835                 break;
1836         }
1837
1838         case LFUN_THESAURUS_ENTRY: {
1839                 docstring arg = cmd.argument();
1840                 if (arg.empty()) {
1841                         arg = cur.selectionAsString(false);
1842                         // FIXME
1843                         if (arg.size() > 100 || arg.empty()) {
1844                                 // Get word or selection
1845                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1846                                 arg = cur.selectionAsString(false);
1847                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
1848                         }
1849                 }
1850                 bv->showDialog("thesaurus", to_utf8(arg));
1851                 break;
1852         }
1853
1854         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1855                 // Given data, an encoding of the ParagraphParameters
1856                 // generated in the Paragraph dialog, this function sets
1857                 // the current paragraph, or currently selected paragraphs,
1858                 // appropriately.
1859                 // NOTE: This function overrides all existing settings.
1860                 setParagraphs(cur, cmd.argument());
1861                 cur.message(_("Paragraph layout set"));
1862                 break;
1863         }
1864
1865         case LFUN_PARAGRAPH_PARAMS: {
1866                 // Given data, an encoding of the ParagraphParameters as we'd
1867                 // find them in a LyX file, this function modifies the current paragraph,
1868                 // or currently selected paragraphs.
1869                 // NOTE: This function only modifies, and does not override, existing
1870                 // settings.
1871                 setParagraphs(cur, cmd.argument(), true);
1872                 cur.message(_("Paragraph layout set"));
1873                 break;
1874         }
1875
1876         case LFUN_ESCAPE:
1877                 if (cur.selection()) {
1878                         cur.setSelection(false);
1879                 } else {
1880                         cur.undispatched();
1881                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1882                         // correct, but I'm not 100% sure -- dov, 071019
1883                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1884                 }
1885                 break;
1886
1887         case LFUN_OUTLINE_UP:
1888                 outline(OutlineUp, cur);
1889                 setCursor(cur, cur.pit(), 0);
1890                 cur.buffer()->updateLabels();
1891                 needsUpdate = true;
1892                 break;
1893
1894         case LFUN_OUTLINE_DOWN:
1895                 outline(OutlineDown, cur);
1896                 setCursor(cur, cur.pit(), 0);
1897                 cur.buffer()->updateLabels();
1898                 needsUpdate = true;
1899                 break;
1900
1901         case LFUN_OUTLINE_IN:
1902                 outline(OutlineIn, cur);
1903                 cur.buffer()->updateLabels();
1904                 needsUpdate = true;
1905                 break;
1906
1907         case LFUN_OUTLINE_OUT:
1908                 outline(OutlineOut, cur);
1909                 cur.buffer()->updateLabels();
1910                 needsUpdate = true;
1911                 break;
1912
1913         default:
1914                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
1915                 cur.undispatched();
1916                 break;
1917         }
1918
1919         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1920
1921         // FIXME: The cursor flag is reset two lines below
1922         // so we need to check here if some of the LFUN did touch that.
1923         // for now only Text::erase() and Text::backspace() do that.
1924         // The plan is to verify all the LFUNs and then to remove this
1925         // singleParUpdate boolean altogether.
1926         if (cur.result().update() & Update::Force) {
1927                 singleParUpdate = false;
1928                 needsUpdate = true;
1929         }
1930
1931         // FIXME: the following code should go in favor of fine grained
1932         // update flag treatment.
1933         if (singleParUpdate) {
1934                 // Inserting characters does not change par height in general. So, try
1935                 // to update _only_ this paragraph. BufferView will detect if a full
1936                 // metrics update is needed anyway.
1937                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1938                 return;
1939         }
1940
1941         if (!needsUpdate
1942             && &oldTopSlice.inset() == &cur.inset()
1943             && oldTopSlice.idx() == cur.idx()
1944             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1945             && !cur.selection())
1946                 // FIXME: it would be better if we could just do this
1947                 //
1948                 //if (cur.result().update() != Update::FitCursor)
1949                 //      cur.noUpdate();
1950                 //
1951                 // But some LFUNs do not set Update::FitCursor when needed, so we
1952                 // do it for all. This is not very harmfull as FitCursor will provoke
1953                 // a full redraw only if needed but still, a proper review of all LFUN
1954                 // should be done and this needsUpdate boolean can then be removed.
1955                 cur.updateFlags(Update::FitCursor);
1956         else
1957                 cur.updateFlags(Update::Force | Update::FitCursor);
1958 }
1959
1960
1961 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1962                         FuncStatus & flag) const
1963 {
1964         LASSERT(cur.text() == this, /**/);
1965
1966         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
1967         bool enable = true;
1968         InsetCode code = NO_CODE;
1969
1970         switch (cmd.action) {
1971
1972         case LFUN_DEPTH_DECREMENT:
1973                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1974                 break;
1975
1976         case LFUN_DEPTH_INCREMENT:
1977                 enable = changeDepthAllowed(cur, INC_DEPTH);
1978                 break;
1979
1980         case LFUN_APPENDIX:
1981                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1982                 break;
1983
1984         case LFUN_DIALOG_SHOW_NEW_INSET:
1985                 if (cmd.argument() == "bibitem")
1986                         code = BIBITEM_CODE;
1987                 else if (cmd.argument() == "bibtex")
1988                         code = BIBTEX_CODE;
1989                 else if (cmd.argument() == "box")
1990                         code = BOX_CODE;
1991                 else if (cmd.argument() == "branch")
1992                         code = BRANCH_CODE;
1993                 else if (cmd.argument() == "citation")
1994                         code = CITE_CODE;
1995                 else if (cmd.argument() == "ert")
1996                         code = ERT_CODE;
1997                 else if (cmd.argument() == "external")
1998                         code = EXTERNAL_CODE;
1999                 else if (cmd.argument() == "float")
2000                         code = FLOAT_CODE;
2001                 else if (cmd.argument() == "graphics")
2002                         code = GRAPHICS_CODE;
2003                 else if (cmd.argument() == "href")
2004                         code = HYPERLINK_CODE;
2005                 else if (cmd.argument() == "include")
2006                         code = INCLUDE_CODE;
2007                 else if (cmd.argument() == "index")
2008                         code = INDEX_CODE;
2009                 else if (cmd.argument() == "nomenclature")
2010                         code = NOMENCL_CODE;
2011                 else if (cmd.argument() == "label")
2012                         code = LABEL_CODE;
2013                 else if (cmd.argument() == "note")
2014                         code = NOTE_CODE;
2015                 else if (cmd.argument() == "phantom")
2016                         code = PHANTOM_CODE;
2017                 else if (cmd.argument() == "ref")
2018                         code = REF_CODE;
2019                 else if (cmd.argument() == "space")
2020                         code = SPACE_CODE;
2021                 else if (cmd.argument() == "toc")
2022                         code = TOC_CODE;
2023                 else if (cmd.argument() == "vspace")
2024                         code = VSPACE_CODE;
2025                 else if (cmd.argument() == "wrap")
2026                         code = WRAP_CODE;
2027                 else if (cmd.argument() == "listings")
2028                         code = LISTINGS_CODE;
2029                 break;
2030
2031         case LFUN_ERT_INSERT:
2032                 code = ERT_CODE;
2033                 break;
2034         case LFUN_LISTING_INSERT:
2035                 code = LISTINGS_CODE;
2036                 // not allowed in description items
2037                 enable = !inDescriptionItem(cur);
2038                 break;
2039         case LFUN_FOOTNOTE_INSERT:
2040                 code = FOOT_CODE;
2041                 break;
2042         case LFUN_TABULAR_INSERT:
2043                 code = TABULAR_CODE;
2044                 break;
2045         case LFUN_MARGINALNOTE_INSERT:
2046                 code = MARGIN_CODE;
2047                 break;
2048         case LFUN_FLOAT_INSERT:
2049         case LFUN_FLOAT_WIDE_INSERT:
2050                 code = FLOAT_CODE;
2051                 // not allowed in description items
2052                 enable = !inDescriptionItem(cur);
2053                 break;
2054         case LFUN_WRAP_INSERT:
2055                 code = WRAP_CODE;
2056                 // not allowed in description items
2057                 enable = !inDescriptionItem(cur);
2058                 break;
2059         case LFUN_FLOAT_LIST_INSERT:
2060                 code = FLOAT_LIST_CODE;
2061                 break;
2062         case LFUN_CAPTION_INSERT:
2063                 code = CAPTION_CODE;
2064                 // not allowed in description items
2065                 enable = !inDescriptionItem(cur);
2066                 break;
2067         case LFUN_NOTE_INSERT:
2068                 code = NOTE_CODE;
2069                 // in commands (sections etc.) and description items,
2070                 // only Notes are allowed
2071                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2072                           (!cur.paragraph().layout().isCommand()
2073                            && !inDescriptionItem(cur)));
2074                 break;
2075         case LFUN_FLEX_INSERT: {
2076                 code = FLEX_CODE;
2077                 string s = cmd.getArg(0);
2078                 InsetLayout il =
2079                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2080                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2081                     il.lyxtype() != InsetLayout::CUSTOM &&
2082                     il.lyxtype() != InsetLayout::ELEMENT &&
2083                     il.lyxtype ()!= InsetLayout::STANDARD)
2084                         enable = false;
2085                 break;
2086                 }
2087         case LFUN_BOX_INSERT:
2088                 code = BOX_CODE;
2089                 break;
2090         case LFUN_BRANCH_INSERT:
2091                 code = BRANCH_CODE;
2092                 if (cur.buffer()->masterBuffer()->params().branchlist().empty())
2093                         enable = false;
2094                 break;
2095         case LFUN_PHANTOM_INSERT:
2096                 code = PHANTOM_CODE;
2097                 break;
2098         case LFUN_LABEL_INSERT:
2099                 code = LABEL_CODE;
2100                 break;
2101         case LFUN_INFO_INSERT:
2102                 code = INFO_CODE;
2103                 break;
2104         case LFUN_OPTIONAL_INSERT:
2105                 code = OPTARG_CODE;
2106                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2107                         < cur.paragraph().layout().optionalargs;
2108                 break;
2109         case LFUN_INDEX_INSERT:
2110                 code = INDEX_CODE;
2111                 break;
2112         case LFUN_INDEX_PRINT:
2113                 code = INDEX_PRINT_CODE;
2114                 break;
2115         case LFUN_NOMENCL_INSERT:
2116                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2117                         enable = false;
2118                         break;
2119                 }
2120                 code = NOMENCL_CODE;
2121                 break;
2122         case LFUN_NOMENCL_PRINT:
2123                 code = NOMENCL_PRINT_CODE;
2124                 break;
2125         case LFUN_TOC_INSERT:
2126                 code = TOC_CODE;
2127                 break;
2128         case LFUN_HYPERLINK_INSERT:
2129                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2130                         enable = false;
2131                         break;
2132                 }
2133                 code = HYPERLINK_CODE;
2134                 break;
2135         case LFUN_QUOTE_INSERT:
2136                 // always allow this, since we will inset a raw quote
2137                 // if an inset is not allowed.
2138                 break;
2139         case LFUN_SPECIALCHAR_INSERT:
2140                 code = SPECIALCHAR_CODE;
2141                 break;
2142         case LFUN_SPACE_INSERT:
2143                 // slight hack: we know this is allowed in math mode
2144                 if (cur.inTexted())
2145                         code = SPACE_CODE;
2146                 break;
2147
2148         case LFUN_INSET_MODIFY:
2149                 // We need to disable this, because we may get called for a
2150                 // tabular cell via
2151                 // InsetTabular::getStatus() -> InsetText::getStatus()
2152                 // and we don't handle LFUN_INSET_MODIFY.
2153                 enable = false;
2154                 break;
2155
2156         case LFUN_FONT_EMPH:
2157                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2158                 break;
2159
2160         case LFUN_FONT_ITAL:
2161                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2162                 break;
2163
2164         case LFUN_FONT_NOUN:
2165                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2166                 break;
2167
2168         case LFUN_FONT_BOLD:
2169         case LFUN_FONT_BOLDSYMBOL:
2170                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2171                 break;
2172
2173         case LFUN_FONT_SANS:
2174                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2175                 break;
2176
2177         case LFUN_FONT_ROMAN:
2178                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2179                 break;
2180
2181         case LFUN_FONT_TYPEWRITER:
2182                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2183                 break;
2184
2185         case LFUN_CUT:
2186         case LFUN_COPY:
2187                 enable = cur.selection();
2188                 break;
2189
2190         case LFUN_PASTE: {
2191                 if (cmd.argument().empty()) {
2192                         if (theClipboard().isInternal())
2193                                 enable = cap::numberOfSelections() > 0;
2194                         else
2195                                 enable = !theClipboard().empty();
2196                         break;
2197                 }
2198
2199                 // we have an argument
2200                 string const arg = to_utf8(cmd.argument());
2201                 if (isStrUnsignedInt(arg)) {
2202                         // it's a number and therefore means the internal stack
2203                         unsigned int n = convert<unsigned int>(arg);
2204                         enable = cap::numberOfSelections() > n;
2205                         break;
2206                 }
2207
2208                 // explicit graphics type?
2209                 if ((arg == "pdf" && theClipboard().hasGraphicsContents(Clipboard::PdfGraphicsType))
2210                     || (arg == "png" && theClipboard().hasGraphicsContents(Clipboard::PngGraphicsType))
2211                     || (arg == "jpeg" && theClipboard().hasGraphicsContents(Clipboard::JpegGraphicsType))
2212                     || (arg == "linkback" && theClipboard().hasGraphicsContents(Clipboard::LinkBackGraphicsType))) {
2213                         enable = true;
2214                         break;
2215                 }
2216
2217                 // unknown argument
2218                 enable = false;
2219                 break;
2220          }
2221
2222         case LFUN_CLIPBOARD_PASTE:
2223                 enable = !theClipboard().empty();
2224                 break;
2225
2226         case LFUN_PRIMARY_SELECTION_PASTE:
2227                 enable = cur.selection() || !theSelection().empty();
2228                 break;
2229
2230         case LFUN_SELECTION_PASTE:
2231                 enable = cap::selection();
2232                 break;
2233
2234         case LFUN_PARAGRAPH_MOVE_UP:
2235                 enable = cur.pit() > 0 && !cur.selection();
2236                 break;
2237
2238         case LFUN_PARAGRAPH_MOVE_DOWN:
2239                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2240                 break;
2241
2242         case LFUN_INSET_DISSOLVE:
2243                 if (!cmd.argument().empty()) {
2244                         InsetLayout const & il = cur.inset().getLayout(cur.buffer()->params());
2245                         InsetLayout::InsetLyXType const type = 
2246                                         translateLyXType(to_utf8(cmd.argument()));
2247                         enable = cur.inset().lyxCode() == FLEX_CODE
2248                                  && il.lyxtype() == type;
2249                 } else {
2250                         enable = ((!isMainText(cur.bv().buffer())
2251                                       && cur.inset().nargs() == 1)
2252                                   || (cur.nextInset()
2253                                       && cur.nextInset()->nargs() == 1));
2254                 }
2255                 break;
2256
2257         case LFUN_CHANGE_ACCEPT:
2258         case LFUN_CHANGE_REJECT:
2259                 // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2260                 // In principle, these LFUNs should only be enabled if there
2261                 // is a change at the current position/in the current selection.
2262                 // However, without proper optimizations, this will inevitably
2263                 // result in unacceptable performance - just imagine a user who
2264                 // wants to select the complete content of a long document.
2265                 enable = true;
2266                 break;
2267
2268         case LFUN_OUTLINE_UP:
2269         case LFUN_OUTLINE_DOWN:
2270         case LFUN_OUTLINE_IN:
2271         case LFUN_OUTLINE_OUT:
2272                 // FIXME: LyX is not ready for outlining within inset.
2273                 enable = isMainText(cur.bv().buffer())
2274                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2275                 break;
2276
2277         case LFUN_NEWLINE_INSERT:
2278                 // LaTeX restrictions (labels or empty par)
2279                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2280                 break;
2281
2282         case LFUN_SET_GRAPHICS_GROUP: {
2283                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2284                 if (!ins)
2285                         enable = false;
2286                 else
2287                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2288                 break;
2289         }
2290
2291         case LFUN_NEWPAGE_INSERT:
2292                 // not allowed in description items
2293                 enable = !inDescriptionItem(cur);
2294                 break;
2295
2296         case LFUN_MATH_INSERT:
2297         case LFUN_MATH_MATRIX:
2298         case LFUN_MATH_DELIM:
2299         case LFUN_MATH_BIGDELIM:
2300                 // not allowed in ERT, for example.
2301                 enable = cur.inset().insetAllowed(MATH_CODE);
2302                 break;
2303
2304         case LFUN_DATE_INSERT: {
2305                 string const format = cmd.argument().empty()
2306                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2307                 enable = support::os::is_valid_strftime(format);
2308                 break;
2309         }
2310
2311         case LFUN_WORD_DELETE_FORWARD:
2312         case LFUN_WORD_DELETE_BACKWARD:
2313         case LFUN_LINE_DELETE:
2314         case LFUN_WORD_FORWARD:
2315         case LFUN_WORD_BACKWARD:
2316         case LFUN_WORD_RIGHT:
2317         case LFUN_WORD_LEFT:
2318         case LFUN_CHAR_FORWARD:
2319         case LFUN_CHAR_FORWARD_SELECT:
2320         case LFUN_CHAR_BACKWARD:
2321         case LFUN_CHAR_BACKWARD_SELECT:
2322         case LFUN_CHAR_LEFT:
2323         case LFUN_CHAR_LEFT_SELECT:
2324         case LFUN_CHAR_RIGHT:
2325         case LFUN_CHAR_RIGHT_SELECT:
2326         case LFUN_UP:
2327         case LFUN_UP_SELECT:
2328         case LFUN_DOWN:
2329         case LFUN_DOWN_SELECT:
2330         case LFUN_PARAGRAPH_UP_SELECT:
2331         case LFUN_PARAGRAPH_DOWN_SELECT:
2332         case LFUN_LINE_BEGIN_SELECT:
2333         case LFUN_LINE_END_SELECT:
2334         case LFUN_WORD_FORWARD_SELECT:
2335         case LFUN_WORD_BACKWARD_SELECT:
2336         case LFUN_WORD_RIGHT_SELECT:
2337         case LFUN_WORD_LEFT_SELECT:
2338         case LFUN_WORD_SELECT:
2339         case LFUN_PARAGRAPH_UP:
2340         case LFUN_PARAGRAPH_DOWN:
2341         case LFUN_LINE_BEGIN:
2342         case LFUN_LINE_END:
2343         case LFUN_CHAR_DELETE_FORWARD:
2344         case LFUN_CHAR_DELETE_BACKWARD:
2345         case LFUN_BREAK_PARAGRAPH:
2346         case LFUN_PARAGRAPH_SPACING:
2347         case LFUN_INSET_INSERT:
2348         case LFUN_WORD_UPCASE:
2349         case LFUN_WORD_LOWCASE:
2350         case LFUN_WORD_CAPITALIZE:
2351         case LFUN_CHARS_TRANSPOSE:
2352         case LFUN_SERVER_GET_XY:
2353         case LFUN_SERVER_SET_XY:
2354         case LFUN_SERVER_GET_LAYOUT:
2355         case LFUN_LAYOUT:
2356         case LFUN_SELF_INSERT:
2357         case LFUN_LINE_INSERT:
2358         case LFUN_MATH_DISPLAY:
2359         case LFUN_MATH_MODE:
2360         case LFUN_MATH_MACRO:
2361         case LFUN_MATH_SUBSCRIPT:
2362         case LFUN_MATH_SUPERSCRIPT:
2363         case LFUN_FONT_DEFAULT:
2364         case LFUN_FONT_UNDERLINE:
2365         case LFUN_FONT_SIZE:
2366         case LFUN_LANGUAGE:
2367         case LFUN_TEXTSTYLE_APPLY:
2368         case LFUN_TEXTSTYLE_UPDATE:
2369         case LFUN_LAYOUT_PARAGRAPH:
2370         case LFUN_PARAGRAPH_UPDATE:
2371         case LFUN_ACCENT_UMLAUT:
2372         case LFUN_ACCENT_CIRCUMFLEX:
2373         case LFUN_ACCENT_GRAVE:
2374         case LFUN_ACCENT_ACUTE:
2375         case LFUN_ACCENT_TILDE:
2376         case LFUN_ACCENT_CEDILLA:
2377         case LFUN_ACCENT_MACRON:
2378         case LFUN_ACCENT_DOT:
2379         case LFUN_ACCENT_UNDERDOT:
2380         case LFUN_ACCENT_UNDERBAR:
2381         case LFUN_ACCENT_CARON:
2382         case LFUN_ACCENT_BREVE:
2383         case LFUN_ACCENT_TIE:
2384         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2385         case LFUN_ACCENT_CIRCLE:
2386         case LFUN_ACCENT_OGONEK:
2387         case LFUN_THESAURUS_ENTRY:
2388         case LFUN_PARAGRAPH_PARAMS_APPLY:
2389         case LFUN_PARAGRAPH_PARAMS:
2390         case LFUN_ESCAPE:
2391         case LFUN_BUFFER_BEGIN:
2392         case LFUN_BUFFER_END:
2393         case LFUN_BUFFER_BEGIN_SELECT:
2394         case LFUN_BUFFER_END_SELECT:
2395         case LFUN_INSET_BEGIN:
2396         case LFUN_INSET_END:
2397         case LFUN_INSET_BEGIN_SELECT:
2398         case LFUN_INSET_END_SELECT:
2399         case LFUN_UNICODE_INSERT:
2400                 // these are handled in our dispatch()
2401                 enable = true;
2402                 break;
2403
2404         default:
2405                 return false;
2406         }
2407
2408         if (code != NO_CODE
2409             && (cur.empty() || !cur.inset().insetAllowed(code)))
2410                 enable = false;
2411
2412         flag.setEnabled(enable);
2413         return true;
2414 }
2415
2416
2417 void Text::pasteString(Cursor & cur, docstring const & clip,
2418                 bool asParagraphs)
2419 {
2420         cur.clearSelection();
2421         if (!clip.empty()) {
2422                 cur.recordUndo();
2423                 if (asParagraphs)
2424                         insertStringAsParagraphs(cur, clip);
2425                 else
2426                         insertStringAsLines(cur, clip);
2427         }
2428 }
2429
2430
2431 // FIXME: an item inset would make things much easier.
2432 bool Text::inDescriptionItem(Cursor & cur) const
2433 {
2434         Paragraph & par = cur.paragraph();
2435         pos_type const pos = cur.pos();
2436         pos_type const body_pos = par.beginOfBody();
2437
2438         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2439             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2440                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2441                 return false;
2442
2443         return (pos < body_pos
2444                 || (pos == body_pos
2445                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2446 }
2447
2448 } // namespace lyx