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