]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
font_metrics part 1
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #ifdef __GNUG__
4 #pragma implementation
5 #endif
6
7 #include "BufferView_pimpl.h"
8 #include "frontends/WorkArea.h"
9 #include "frontends/screen.h"
10 #include "lyxtext.h"
11 #include "lyxrow.h"
12 #include "paragraph.h"
13 #include "frontends/LyXView.h"
14 #include "commandtags.h"
15 #include "lyxfunc.h"
16 #include "debug.h"
17 #include "bufferview_funcs.h"
18 #include "TextCache.h"
19 #include "bufferlist.h"
20 #include "lyxrc.h"
21 #include "intl.h"
22 // added for Dispatch functions
23 #include "lyx_cb.h"
24 #include "lyx_main.h"
25 #include "FloatList.h"
26 #include "gettext.h"
27 #include "ParagraphParameters.h"
28 #include "undo_funcs.h"
29 #include "lyxtextclasslist.h"
30
31 #include "frontends/Dialogs.h"
32 #include "frontends/Alert.h"
33 #include "frontends/FileDialog.h"
34
35 #include "insets/insetbib.h"
36 #include "insets/insettext.h"
37 #include "insets/inseturl.h"
38 #include "insets/insetlatexaccent.h"
39 #include "insets/insettoc.h"
40 #include "insets/insetref.h"
41 #include "insets/insetparent.h"
42 #include "insets/insetindex.h"
43 #include "insets/insetnote.h"
44 #include "insets/insetinclude.h"
45 #include "insets/insetcite.h"
46 #include "insets/insetert.h"
47 #include "insets/insetexternal.h"
48 #include "insets/insetgraphics.h"
49 #include "insets/insetfoot.h"
50 #include "insets/insetmarginal.h"
51 #include "insets/insetminipage.h"
52 #include "insets/insetfloat.h"
53 #include "insets/insettabular.h"
54 #if 0
55 #include "insets/insettheorem.h"
56 #include "insets/insetlist.h"
57 #endif
58 #include "insets/insetcaption.h"
59 #include "insets/insetfloatlist.h"
60 #include "insets/insetspecialchar.h"
61
62 #include "mathed/formulabase.h"
63
64 #include "support/LAssert.h"
65 #include "support/lstrings.h"
66 #include "support/filetools.h"
67 #include "support/lyxfunctional.h"
68
69 #include <ctime>
70 #include <unistd.h>
71 #include <sys/wait.h>
72 #include <clocale>
73
74
75 extern string current_layout;
76
77 using std::vector;
78 using std::find_if;
79 using std::find;
80 using std::pair;
81 using std::endl;
82 using std::make_pair;
83 using std::min;
84 using SigC::slot;
85
86 using lyx::pos_type;
87 using lyx::textclass_type;
88
89 /* the selection possible is needed, that only motion events are
90  * used, where the bottom press event was on the drawing area too */
91 bool selection_possible = false;
92
93 extern BufferList bufferlist;
94 extern char ascii_type;
95
96 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
97
98
99 namespace {
100
101 const unsigned int saved_positions_num = 20;
102
103 inline
104 void waitForX()
105 {
106         XSync(fl_get_display(), 0);
107 }
108
109
110 void SetXtermCursor(Window win)
111 {
112         static Cursor cursor;
113         static bool cursor_undefined = true;
114         if (cursor_undefined) {
115                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
116                 XFlush(fl_get_display());
117                 cursor_undefined = false;
118         }
119         XDefineCursor(fl_get_display(), win, cursor);
120         XFlush(fl_get_display());
121 }
122
123 } // anon namespace
124
125
126 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
127              int xpos, int ypos, int width, int height)
128         : bv_(b), owner_(o), buffer_(0),
129           current_scrollbar_value(0), cursor_timeout(400),
130           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
131           inset_slept(false)
132 {
133         // Setup the signals
134         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
135         workarea_.workAreaExpose
136                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
137         workarea_.workAreaEnter
138                 .connect(slot(this, &BufferView::Pimpl::enterView));
139         workarea_.workAreaLeave
140                 .connect(slot(this, &BufferView::Pimpl::leaveView));
141         workarea_.workAreaButtonPress
142                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
143         workarea_.workAreaButtonRelease
144                 .connect(slot(this,
145                               &BufferView::Pimpl::workAreaButtonRelease));
146         workarea_.workAreaMotionNotify
147                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
148         workarea_.workAreaDoubleClick
149                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
150         workarea_.workAreaTripleClick
151                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
152         workarea_.workAreaKeyPress
153                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
154         workarea_.selectionRequested
155                 .connect(slot(this, &BufferView::Pimpl::selectionRequested));
156         workarea_.selectionLost
157                 .connect(slot(this, &BufferView::Pimpl::selectionLost));
158
159         cursor_timeout.timeout.connect(slot(this,
160                                             &BufferView::Pimpl::cursorToggle));
161         cursor_timeout.start();
162         workarea_.setFocus();
163         saved_positions.resize(saved_positions_num);
164 }
165
166
167 Painter & BufferView::Pimpl::painter()
168 {
169         return workarea_.getPainter();
170 }
171
172
173 void BufferView::Pimpl::buffer(Buffer * b)
174 {
175         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
176                             << b << ")" << endl;
177         if (buffer_) {
178 #if 0
179                 insetSleep();
180 #endif
181                 buffer_->delUser(bv_);
182
183                 // Put the old text into the TextCache, but
184                 // only if the buffer is still loaded.
185                 // Also set the owner of the test to 0
186                 //              bv_->text->owner(0);
187                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
188                 if (lyxerr.debugging())
189                         textcache.show(lyxerr, "BufferView::buffer");
190
191                 bv_->text = 0;
192         }
193
194         // Set current buffer
195         buffer_ = b;
196
197         if (bufferlist.getState() == BufferList::CLOSING) return;
198
199         // Nuke old image
200         // screen is always deleted when the buffer is changed.
201         screen_.reset(0);
202
203         // If we are closing the buffer, use the first buffer as current
204         if (!buffer_) {
205                 buffer_ = bufferlist.first();
206         }
207
208         if (buffer_) {
209                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
210                 buffer_->addUser(bv_);
211                 // If we don't have a text object for this, we make one
212                 if (bv_->text == 0) {
213                         resizeCurrentBuffer();
214                 } else {
215                         updateScreen();
216                         updateScrollbar();
217                 }
218                 bv_->text->first_y = screen_->topCursorVisible(bv_->text);
219                 owner_->updateMenubar();
220                 owner_->updateToolbar();
221                 // Similarly, buffer-dependent dialogs should be updated or
222                 // hidden. This should go here because some dialogs (eg ToC)
223                 // require bv_->text.
224                 owner_->getDialogs()->updateBufferDependent(true);
225                 redraw();
226 #if 0
227                 insetWakeup();
228 #endif
229         } else {
230                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
231                 owner_->updateMenubar();
232                 owner_->updateToolbar();
233                 owner_->getDialogs()->hideBufferDependent();
234                 updateScrollbar();
235                 workarea_.redraw();
236
237                 // Also remove all remaining text's from the testcache.
238                 // (there should not be any!) (if there is any it is a
239                 // bug!)
240                 if (lyxerr.debugging())
241                         textcache.show(lyxerr, "buffer delete all");
242                 textcache.clear();
243         }
244         // should update layoutchoice even if we don't have a buffer.
245         owner_->updateLayoutChoice();
246
247         owner_->updateWindowTitle();
248 }
249
250
251 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
252 {
253         workarea_.resize(xpos, ypos, width, height);
254         update(bv_->text, SELECT);
255         redraw();
256 }
257
258
259 void BufferView::Pimpl::resize()
260 {
261         if (buffer_)
262                 resizeCurrentBuffer();
263 }
264
265
266 void BufferView::Pimpl::redraw()
267 {
268         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
269         workarea_.redraw();
270 }
271
272
273 bool BufferView::Pimpl::fitCursor()
274 {
275         lyx::Assert(screen_.get());
276
277         bool ret;
278
279         if (bv_->theLockingInset()) {
280                 bv_->theLockingInset()->fitInsetCursor(bv_);
281                 ret = true;
282         } else {
283                 ret = screen_->fitCursor(bv_->text, bv_);
284         }
285
286         bv_->owner()->getDialogs()->updateParagraph();
287         if (ret)
288             updateScrollbar();
289         return ret;
290 }
291
292
293 void BufferView::Pimpl::redoCurrentBuffer()
294 {
295         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
296         if (buffer_ && bv_->text) {
297                 resize();
298                 owner_->updateLayoutChoice();
299         }
300 }
301
302
303 int BufferView::Pimpl::resizeCurrentBuffer()
304 {
305         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
306
307         Paragraph * par = 0;
308         Paragraph * selstartpar = 0;
309         Paragraph * selendpar = 0;
310         UpdatableInset * the_locking_inset = 0;
311
312         pos_type pos = 0;
313         pos_type selstartpos = 0;
314         pos_type selendpos = 0;
315         bool selection = false;
316         bool mark_set  = false;
317
318         owner_->prohibitInput();
319
320         owner_->message(_("Formatting document..."));
321
322         if (bv_->text) {
323                 par = bv_->text->cursor.par();
324                 pos = bv_->text->cursor.pos();
325                 selstartpar = bv_->text->selection.start.par();
326                 selstartpos = bv_->text->selection.start.pos();
327                 selendpar = bv_->text->selection.end.par();
328                 selendpos = bv_->text->selection.end.pos();
329                 selection = bv_->text->selection.set();
330                 mark_set = bv_->text->selection.mark();
331                 the_locking_inset = bv_->theLockingInset();
332                 buffer_->resizeInsets(bv_);
333                 // I don't think the delete and new are necessary here we just could
334                 // call only init! (Jug 20020419)
335                 delete bv_->text;
336                 bv_->text = new LyXText(bv_);
337                 bv_->text->init(bv_);
338         } else {
339                 // See if we have a text in TextCache that fits
340                 // the new buffer_ with the correct width.
341                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
342                 if (bv_->text) {
343                         if (lyxerr.debugging()) {
344                                 lyxerr << "Found a LyXText that fits:\n";
345                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
346                         }
347                         // Set the owner of the newly found text
348                         //      bv_->text->owner(bv_);
349                         if (lyxerr.debugging())
350                                 textcache.show(lyxerr, "resizeCurrentBuffer");
351                 } else {
352                         bv_->text = new LyXText(bv_);
353                         bv_->text->init(bv_);
354                         //buffer_->resizeInsets(bv_);
355                 }
356         }
357
358         updateScreen();
359
360         if (par) {
361                 bv_->text->selection.set(true);
362                 // At this point just to avoid the Delete-Empty-Paragraph-
363                 // Mechanism when setting the cursor.
364                 bv_->text->selection.mark(mark_set);
365                 if (selection) {
366                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
367                         bv_->text->selection.cursor = bv_->text->cursor;
368                         bv_->text->setCursor(bv_, selendpar, selendpos);
369                         bv_->text->setSelection(bv_);
370                         bv_->text->setCursor(bv_, par, pos);
371                 } else {
372                         bv_->text->setCursor(bv_, par, pos);
373                         bv_->text->selection.cursor = bv_->text->cursor;
374                         bv_->text->selection.set(false);
375                 }
376                 // remake the inset locking
377                 bv_->theLockingInset(the_locking_inset);
378         }
379
380         bv_->text->first_y = screen_->topCursorVisible(bv_->text);
381
382         // this will scroll the screen such that the cursor becomes visible
383         updateScrollbar();
384         redraw();
385
386         setState();
387         owner_->allowInput();
388
389         /// clear the "Formatting Document" message
390         owner_->message("");
391
392         return 0;
393 }
394
395
396 void BufferView::Pimpl::updateScreen()
397 {
398         // Regenerate the screen.
399         screen_.reset(new LyXScreen(workarea_));
400 }
401
402
403 void BufferView::Pimpl::updateScrollbar()
404 {
405         if (!bv_->text) {
406                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
407                 workarea_.setScrollbar(0, 1.0);
408                 return;
409         }
410
411         long const text_height = bv_->text->height;
412         long const work_height = workarea_.height();
413
414         double const lineh = bv_->text->defaultHeight();
415         double const slider_size =
416                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
417
418         lyxerr[Debug::GUI] << "text_height now " << text_height << endl;
419         lyxerr[Debug::GUI] << "work_height " << work_height << endl;
420
421         /* If the text is smaller than the working area, the scrollbar
422          * maximum must be the working area height. No scrolling will
423          * be possible */
424         if (text_height <= work_height) {
425                 lyxerr[Debug::GUI] << "doc smaller than workarea !" << endl;
426                 workarea_.setScrollbarBounds(0.0, 0.0);
427                 current_scrollbar_value = bv_->text->first_y;
428                 workarea_.setScrollbar(current_scrollbar_value, 1.0);
429                 return;
430         }
431
432         workarea_.setScrollbarBounds(0.0, text_height - work_height);
433         workarea_.setScrollbarIncrements(lineh);
434         current_scrollbar_value = bv_->text->first_y;
435         workarea_.setScrollbar(current_scrollbar_value, slider_size);
436 }
437
438
439 // Callback for scrollbar slider
440 void BufferView::Pimpl::scrollCB(double value)
441 {
442         lyxerr[Debug::GUI] << "scrollCB of " << value << endl;
443
444         if (!buffer_) return;
445
446         current_scrollbar_value = long(value);
447
448         if (current_scrollbar_value < 0)
449                 current_scrollbar_value = 0;
450
451         if (!screen_.get())
452                 return;
453
454         screen_->draw(bv_->text, bv_, current_scrollbar_value);
455
456         if (!lyxrc.cursor_follows_scrollbar) {
457                 waitForX();
458                 return;
459         }
460
461         LyXText * vbt = bv_->text;
462
463         int const height = vbt->defaultHeight();
464         int const first = static_cast<int>((bv_->text->first_y + height));
465         int const last = static_cast<int>((bv_->text->first_y + workarea_.height() - height));
466
467         if (vbt->cursor.y() < first)
468                 vbt->setCursorFromCoordinates(bv_, 0, first);
469         else if (vbt->cursor.y() > last)
470                 vbt->setCursorFromCoordinates(bv_, 0, last);
471
472         waitForX();
473 }
474
475
476 int BufferView::Pimpl::scrollUp(long time)
477 {
478         if (!buffer_ || !screen_.get())
479                 return 0;
480
481         double value = workarea_.getScrollbarValue();
482
483         if (value == 0)
484                 return 0;
485
486 #if 1
487         float add_value =  (bv_->text->defaultHeight()
488                             + float(time) * float(time) * 0.125);
489
490         if (add_value > workarea_.height())
491                 add_value = float(workarea_.height() -
492                                   bv_->text->defaultHeight());
493 #else
494         float add_value =  float(workarea_.height()) * float(time) / 100;
495 #endif
496
497         value -= add_value;
498
499         if (value < 0)
500                 value = 0;
501
502         workarea_.setScrollbarValue(value);
503
504         scrollCB(value);
505         return 0;
506 }
507
508
509 int BufferView::Pimpl::scrollDown(long time)
510 {
511         if (!buffer_ || !screen_.get())
512                 return 0;
513
514         double value = workarea_.getScrollbarValue();
515         pair<float, float> p = workarea_.getScrollbarBounds();
516         double const max = p.second;
517
518         if (value == max)
519                 return 0;
520
521 #if 1
522         float add_value =  (bv_->text->defaultHeight()
523                             + float(time) * float(time) * 0.125);
524
525         if (add_value > workarea_.height())
526                 add_value = float(workarea_.height() -
527                                   bv_->text->defaultHeight());
528 #else
529         float add_value =  float(workarea_.height()) * float(time) / 100;
530 #endif
531
532         value += add_value;
533
534         if (value > max)
535                 value = max;
536
537         workarea_.setScrollbarValue(value);
538
539         scrollCB(value);
540         return 0;
541 }
542
543
544 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
545 {
546         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
547 }
548
549
550 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
551 {
552         // Only use motion with button 1
553         if (!(state & Button1MotionMask))
554                 return;
555
556         if (!buffer_ || !screen_.get()) return;
557
558         // Check for inset locking
559         if (bv_->theLockingInset()) {
560                 LyXCursor cursor = bv_->text->cursor;
561                 LyXFont font = bv_->text->getFont(buffer_,
562                                                   cursor.par(), cursor.pos());
563                 int width = bv_->theLockingInset()->width(bv_, font);
564                 int inset_x = font.isVisibleRightToLeft()
565                         ? cursor.ix() - width : cursor.ix();
566                 int start_x = inset_x + bv_->theLockingInset()->scroll();
567                 bv_->theLockingInset()->
568                         insetMotionNotify(bv_,
569                                           x - start_x,
570                                           y - cursor.iy() + bv_->text->first_y,
571                                           state);
572                 return;
573         }
574
575         /* The test for not selection possible is needed, that only motion
576            events are used, where the bottom press event was on
577            the drawing area too */
578         if (!selection_possible)
579                 return;
580
581         screen_->hideCursor();
582 #if 0
583         int y_before = bv_->text->cursor.y();
584 #endif
585         Row * cursorrow = bv_->text->cursor.row();
586         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
587 #if 0
588         // sorry for this but I have a strange error that the y value jumps at
589         // a certain point. This seems like an error in my xforms library or
590         // in some other local environment, but I would like to leave this here
591         // for the moment until I can remove this (Jug 20020418)
592         if (y_before < bv_->text->cursor.y())
593                 lyxerr << y_before << ":" << bv_->text->cursor.y() << endl;
594 #endif
595         // This is to allow jumping over large insets
596         if (cursorrow == bv_->text->cursor.row()) {
597                 if (y >= int(workarea_.height())) {
598                         bv_->text->cursorDown(bv_, false);
599                 } else if (y < 0) {
600                         bv_->text->cursorUp(bv_, false);
601                 }
602         }
603
604         if (!bv_->text->selection.set())
605                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
606
607         bv_->text->setSelection(bv_);
608         screen_->toggleToggle(bv_->text, bv_);
609         fitCursor();
610         showCursor();
611 }
612
613
614 // Single-click on work area
615 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
616                                             unsigned int button)
617 {
618         if (!buffer_ || !screen_.get())
619                 return;
620
621         // ok ok, this is a hack.
622         // Why??? (Jug20020424)
623         if (button == 4 || button == 5) {
624                 switch (button) {
625                 case 4:
626                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
627                         break;
628                 case 5:
629                         scrollDown(lyxrc.wheel_jump);
630                         break;
631                 }
632                 // We shouldn't go further down as we really should only do the
633                 // scrolling and be done with this. Otherwise we may open some
634                 // dialogs (Jug 20020424).
635                 return;
636         }
637
638         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
639
640         // Middle button press pastes if we have a selection
641         // We do this here as if the selection was inside an inset
642         // it could get cleared on the unlocking of the inset so
643         // we have to check this first
644         bool paste_internally = false;
645         if (button == 2 && bv_->getLyXText()->selection.set()) {
646                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
647                 paste_internally = true;
648         }
649
650         int const screen_first = bv_->text->first_y;
651
652         if (bv_->theLockingInset()) {
653                 // We are in inset locking mode
654
655                 /* Check whether the inset was hit. If not reset mode,
656                    otherwise give the event to the inset */
657                 if (inset_hit == bv_->theLockingInset()) {
658                         bv_->theLockingInset()->
659                                 insetButtonPress(bv_,xpos, ypos,button);
660                         return;
661                 } else {
662                         bv_->unlockInset(bv_->theLockingInset());
663                 }
664         }
665
666         if (!inset_hit)
667                 selection_possible = true;
668         screen_->hideCursor();
669
670         // Clear the selection
671         screen_->toggleSelection(bv_->text, bv_);
672         bv_->text->clearSelection();
673         bv_->text->fullRebreak(bv_);
674         update();
675         updateScrollbar();
676
677         // Single left click in math inset?
678         if (isHighlyEditableInset(inset_hit)) {
679                 // Highly editable inset, like math
680                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
681                 selection_possible = false;
682                 owner_->updateLayoutChoice();
683                 owner_->message(inset->editMessage());
684                 //inset->edit(bv_, xpos, ypos, button);
685                 // We just have to lock the inset before calling a PressEvent on it!
686                 // we don't need the edit() call here! (Jug20020329)
687                 if (!bv_->lockInset(inset)) {
688                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
689                 }
690                 inset->insetButtonPress(bv_, xpos, ypos, button);
691                 return;
692         }
693         // I'm not sure we should continue here if we hit an inset (Jug20020403)
694
695         // Right click on a footnote flag opens float menu
696         if (button == 3) {
697                 selection_possible = false;
698                 return;
699         }
700
701         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
702                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
703         finishUndo();
704         bv_->text->selection.cursor = bv_->text->cursor;
705         bv_->text->cursor.x_fix(bv_->text->cursor.x());
706
707         owner_->updateLayoutChoice();
708         if (fitCursor()) {
709                 selection_possible = false;
710         }
711
712         // Insert primary selection with middle mouse
713         // if there is a local selection in the current buffer,
714         // insert this
715         if (button == 2) {
716                 if (paste_internally)
717                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
718                 else
719                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
720                                                        "paragraph");
721                 selection_possible = false;
722                 return;
723         }
724 }
725
726
727 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button)
728 {
729         // select a word
730         if (!buffer_)
731                 return;
732
733         LyXText * text = bv_->getLyXText();
734
735         if (text->bv_owner && bv_->theLockingInset())
736                 return;
737
738         if (screen_.get() && button == 1) {
739                 if (text->bv_owner) {
740                         screen_->hideCursor();
741                         screen_->toggleSelection(text, bv_);
742                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
743                         screen_->toggleSelection(text, bv_, false);
744                 } else {
745                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
746                 }
747                 /* This will fit the cursor on the screen
748                  * if necessary */
749                 update(text, BufferView::SELECT|BufferView::FITCUR);
750         }
751 }
752
753
754 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
755 {
756         // select a line
757         if (!buffer_)
758                 return;
759
760         LyXText * text = bv_->getLyXText();
761
762         if (text->bv_owner && bv_->theLockingInset())
763             return;
764
765         if (screen_.get() && (button == 1)) {
766                 if (text->bv_owner) {
767                         screen_->hideCursor();
768                         screen_->toggleSelection(text, bv_);
769                 }
770                 text->cursorHome(bv_);
771                 text->selection.cursor = text->cursor;
772                 text->cursorEnd(bv_);
773                 text->setSelection(bv_);
774                 if (text->bv_owner) {
775                         screen_->toggleSelection(text, bv_, false);
776                 }
777                 /* This will fit the cursor on the screen
778                  * if necessary */
779                 update(text, BufferView::SELECT|BufferView::FITCUR);
780         }
781 }
782
783
784 void BufferView::Pimpl::selectionRequested()
785 {
786         static string sel;
787
788         if (!available())
789                 return;
790
791         LyXText * text = bv_->getLyXText();
792
793         if (text->selection.set() &&
794                 (!bv_->text->xsel_cache.set() ||
795                  text->selection.start != bv_->text->xsel_cache.start ||
796                  text->selection.end != bv_->text->xsel_cache.end))
797         {
798                 bv_->text->xsel_cache = text->selection;
799                 sel = text->selectionAsString(bv_->buffer(), false);
800         } else if (!text->selection.set()) {
801                 sel = string();
802                 bv_->text->xsel_cache.set(false);
803         }
804         if (!sel.empty()) {
805                 workarea_.putClipboard(sel);
806         }
807 }
808
809
810 void BufferView::Pimpl::selectionLost()
811 {
812         if (active() && available()) {
813                 hideCursor();
814                 toggleSelection();
815                 bv_->getLyXText()->clearSelection();
816                 showCursor();
817                 bv_->text->xsel_cache.set(false);
818         }
819 }
820
821
822 void BufferView::Pimpl::enterView()
823 {
824         if (active() && available()) {
825                 SetXtermCursor(workarea_.getWin());
826                 using_xterm_cursor = true;
827         }
828 }
829
830
831 void BufferView::Pimpl::leaveView()
832 {
833         if (using_xterm_cursor) {
834                 XUndefineCursor(fl_get_display(), workarea_.getWin());
835                 using_xterm_cursor = false;
836         }
837 }
838
839
840 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
841                                               unsigned int button)
842 {
843         // do nothing if we used the mouse wheel
844         if (!buffer_ || !screen_.get() || button == 4 || button == 5)
845                 return;
846
847         // If we hit an inset, we have the inset coordinates in these
848         // and inset_hit points to the inset.  If we do not hit an
849         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
850         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
851
852         if (bv_->theLockingInset()) {
853                 // We are in inset locking mode.
854
855                 /* LyX does a kind of work-area grabbing for insets.
856                    Only a ButtonPress Event outside the inset will
857                    force a insetUnlock. */
858                 bv_->theLockingInset()->
859                         insetButtonRelease(bv_, x, y, button);
860                 return;
861         }
862
863         selection_possible = false;
864
865         if (button == 2)
866                 return;
867
868         // finish selection
869         if (button == 1) {
870                 workarea_.haveSelection(bv_->getLyXText()->selection.set());
871         }
872
873         setState();
874         owner_->showState();
875         owner_->updateMenubar();
876         owner_->updateToolbar();
877
878         // Did we hit an editable inset?
879         if (inset_hit) {
880                 selection_possible = false;
881
882                 // if we reach this point with a selection, it
883                 // must mean we are currently selecting.
884                 // But we don't want to open the inset
885                 // because that is annoying for the user.
886                 // So just pretend we didn't hit it.
887                 // this is OK because a "kosher" ButtonRelease
888                 // will follow a ButtonPress that clears
889                 // the selection.
890                 // Note this also fixes selection drawing
891                 // problems if we end up opening an inset
892                 if (bv_->getLyXText()->selection.set())
893                         return;
894
895                 // CHECK fix this proper in 0.13
896                 // well, maybe 13.0 !!!!!!!!!
897
898                 // Following a ref shouldn't issue
899                 // a push on the undo-stack
900                 // anylonger, now that we have
901                 // keybindings for following
902                 // references and returning from
903                 // references.  IMHO though, it
904                 // should be the inset's own business
905                 // to push or not push on the undo
906                 // stack. They don't *have* to
907                 // alter the document...
908                 // (Joacim)
909                 // ...or maybe the SetCursorParUndo()
910                 // below isn't necessary at all anylonger?
911                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
912                         setCursorParUndo(bv_);
913                 }
914
915                 owner_->message(inset_hit->editMessage());
916
917                 if (isHighlyEditableInset(inset_hit)) {
918                         // Highly editable inset, like math
919                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
920                         inset->insetButtonRelease(bv_, x, y, button);
921                 } else {
922                         inset_hit->insetButtonRelease(bv_, x, y, button);
923                         // IMO this is a grosshack! Inset's should be changed so that
924                         // they call the actions they have to do with the insetButtonRel.
925                         // function and not in the edit(). This should be changed
926                         // (Jug 20020329)
927                         inset_hit->edit(bv_, x, y, button);
928                 }
929                 return;
930         }
931
932         // Maybe we want to edit a bibitem ale970302
933         if (bv_->text->cursor.par()->bibkey && x < 20 +
934             bibitemMaxWidth(bv_, textclasslist[buffer_->params.textclass].defaultfont())) {
935                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
936         }
937
938         return;
939 }
940
941
942 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
943                                        LyXCursor const & cursor) const
944 {
945         Paragraph /*const*/ & par = *cursor.par();
946         pos_type const pos = cursor.pos();
947
948         lyx::Assert(par.getInset(pos));
949
950         Inset const & inset(*par.getInset(pos));
951
952         LyXFont const & font = text.getFont(buffer_, &par, pos);
953
954         int const width = inset.width(bv_, font);
955         int const inset_x = font.isVisibleRightToLeft()
956                 ? (cursor.ix() - width) : cursor.ix();
957
958         return Box(
959                 inset_x + inset.scroll(),
960                 inset_x + width,
961                 cursor.iy() - inset.ascent(bv_, font),
962                 cursor.iy() + inset.descent(bv_, font));
963 }
964
965
966 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
967                                       LyXCursor const & cursor,
968                                       int & x, int & y) const
969 {
970         pos_type const pos(cursor.pos());
971         Paragraph /*const*/ & par(*cursor.par());
972
973         if (pos >= par.size() || !par.isInset(pos)) {
974                 return 0;
975         }
976
977         Inset /*const*/ * inset = par.getInset(pos);
978
979         if (!isEditableInset(inset)) {
980                 return 0;
981         }
982
983         Box b(insetDimensions(text, cursor));
984
985         if (!b.contained(x, y)) {
986                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
987                         << " box " << b << endl;
988                 return 0;
989         }
990
991         text.setCursor(bv_, &par, pos, true);
992
993         x -= b.x1;
994         // The origin of an inset is on the baseline
995         y -= text.cursor.iy();
996
997         return inset;
998 }
999
1000
1001 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
1002 {
1003         if (!screen_.get())
1004                 return 0;
1005
1006         int y_tmp = y + text->first_y;
1007
1008         LyXCursor cursor;
1009         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
1010
1011         Inset * inset(checkInset(*text, cursor, x, y_tmp));
1012
1013         if (inset) {
1014                 y = y_tmp;
1015                 return inset;
1016         }
1017
1018         // look at previous position
1019
1020         if (cursor.pos() == 0) {
1021                 return 0;
1022         }
1023
1024         // move back one
1025         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
1026
1027         inset = checkInset(*text, cursor, x, y_tmp);
1028         if (inset) {
1029                 y = y_tmp;
1030         }
1031         return inset;
1032 }
1033
1034
1035 void BufferView::Pimpl::workAreaExpose()
1036 {
1037         static int work_area_width;
1038         static unsigned int work_area_height;
1039
1040         bool const widthChange = workarea_.workWidth() != work_area_width;
1041         bool const heightChange = workarea_.height() != work_area_height;
1042
1043         // update from work area
1044         work_area_width = workarea_.workWidth();
1045         work_area_height = workarea_.height();
1046         if (buffer_ != 0) {
1047                 if (widthChange) {
1048                         // The visible LyXView need a resize
1049                         owner_->resize();
1050
1051                         // Remove all texts from the textcache
1052                         // This is not _really_ what we want to do. What
1053                         // we really want to do is to delete in textcache
1054                         // that does not have a BufferView with matching
1055                         // width, but as long as we have only one BufferView
1056                         // deleting all gives the same result.
1057                         if (lyxerr.debugging())
1058                                 textcache.show(lyxerr, "Expose delete all");
1059                         textcache.clear();
1060                         buffer_->resizeInsets(bv_);
1061                 } else if (heightChange) {
1062                         // Rebuild image of current screen
1063                         updateScreen();
1064                         // fitCursor() ensures we don't jump back
1065                         // to the start of the document on vertical
1066                         // resize
1067                         fitCursor();
1068
1069                         // The main window size has changed, repaint most stuff
1070                         redraw();
1071                 } else if (screen_.get())
1072                     screen_->redraw(bv_->text, bv_);
1073         } else {
1074                 // Grey box when we don't have a buffer
1075                 workarea_.greyOut();
1076         }
1077
1078         // always make sure that the scrollbar is sane.
1079         updateScrollbar();
1080         owner_->updateLayoutChoice();
1081         return;
1082 }
1083
1084
1085 void BufferView::Pimpl::update()
1086 {
1087         if (screen_.get() &&
1088                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
1089         {
1090                 LyXText::text_status st = bv_->text->status();
1091                 screen_->update(bv_->text, bv_);
1092                 bool fitc = false;
1093                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
1094                         bv_->text->fullRebreak(bv_);
1095                         st = LyXText::NEED_MORE_REFRESH;
1096                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
1097                                              bv_->text->cursor.pos());
1098                         if (bv_->text->selection.set()) {
1099                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
1100                                                      bv_->text->selection.start.par(),
1101                                                      bv_->text->selection.start.pos());
1102                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
1103                                                      bv_->text->selection.end.par(),
1104                                                      bv_->text->selection.end.pos());
1105                         }
1106                         fitc = true;
1107                         bv_->text->status(bv_, st);
1108                         screen_->update(bv_->text, bv_);
1109                 }
1110                 // do this here instead of in the screen::update because of
1111                 // the above loop!
1112                 bv_->text->status(bv_, LyXText::UNCHANGED);
1113                 if (fitc)
1114                         fitCursor();
1115         }
1116 }
1117
1118 // Values used when calling update:
1119 // -3 - update
1120 // -2 - update, move sel_cursor if selection, fitcursor
1121 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1122 //  0 - update, move sel_cursor if selection, fitcursor
1123 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1124 //  3 - update, move sel_cursor if selection
1125 //
1126 // update -
1127 // a simple redraw of the parts that need refresh
1128 //
1129 // move sel_cursor if selection -
1130 // the text's sel_cursor is moved if there is selection is progress
1131 //
1132 // fitcursor -
1133 // fitCursor() is called and the scrollbar updated
1134 //
1135 // mark dirty -
1136 // the buffer is marked dirty.
1137 //
1138 // enum {
1139 //       UPDATE = 0,
1140 //       SELECT = 1,
1141 //       FITCUR = 2,
1142 //       CHANGE = 4
1143 // };
1144 //
1145 // UPDATE_ONLY = UPDATE;
1146 // UPDATE_SELECT = UPDATE | SELECT;
1147 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1148 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1149 //
1150 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1151 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1152 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1153 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1154 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1155
1156 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1157 {
1158         owner_->updateLayoutChoice();
1159
1160         if (!text->selection.set() && (f & SELECT)) {
1161                 text->selection.cursor = text->cursor;
1162         }
1163
1164         text->fullRebreak(bv_);
1165
1166         if (text->inset_owner) {
1167                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1168             updateInset(text->inset_owner, false);
1169         } else {
1170             update();
1171         }
1172
1173         if ((f & FITCUR)) {
1174                 fitCursor();
1175         }
1176
1177         if ((f & CHANGE)) {
1178                 buffer_->markDirty();
1179         }
1180 }
1181
1182
1183 // Callback for cursor timer
1184 void BufferView::Pimpl::cursorToggle()
1185 {
1186         if (!buffer_) {
1187                 cursor_timeout.restart();
1188                 return;
1189         }
1190
1191         if (!screen_.get()) {
1192                 cursor_timeout.restart();
1193                 return;
1194         }
1195
1196         /* FIXME */
1197         extern void reapSpellchecker(void);
1198         reapSpellchecker();
1199
1200         if (!bv_->theLockingInset()) {
1201                 screen_->cursorToggle(bv_);
1202         } else {
1203                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1204         }
1205
1206         cursor_timeout.restart();
1207 }
1208
1209
1210 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1211 {
1212         if (!text->cursor.row()->previous()) {
1213                 if (text->first_y > 0) {
1214                         int new_y = bv_->text->first_y - workarea_.height();
1215                         screen_->draw(bv_->text, bv_, new_y < 0 ? 0 : new_y);
1216                         updateScrollbar();
1217                 }
1218                 return;
1219         }
1220
1221         int y = text->first_y;
1222         Row * cursorrow = text->cursor.row();
1223
1224         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y);
1225         finishUndo();
1226
1227         int new_y;
1228         if (cursorrow == bv_->text->cursor.row()) {
1229                 // we have a row which is higher than the workarea so we leave the
1230                 // cursor on the start of the row and move only the draw up as soon
1231                 // as we move the cursor or do something while inside the row (it may
1232                 // span several workarea-heights) we'll move to the top again, but this
1233                 // is better than just jump down and only display part of the row.
1234                 new_y = bv_->text->first_y - workarea_.height();
1235         } else {
1236                 if (text->inset_owner) {
1237                         new_y = bv_->text->cursor.iy()
1238                                 + bv_->theLockingInset()->insetInInsetY() + y
1239                                 + text->cursor.row()->height()
1240                                 - workarea_.height() + 1;
1241                 } else {
1242                         new_y = text->cursor.y()
1243                                 - text->cursor.row()->baseline()
1244                                 + text->cursor.row()->height()
1245                                 - workarea_.height() + 1;
1246                 }
1247         }
1248         screen_->draw(bv_->text, bv_,  new_y < 0 ? 0 : new_y);
1249         if (text->cursor.row()->previous()) {
1250                 LyXCursor cur;
1251                 text->setCursor(bv_, cur, text->cursor.row()->previous()->par(),
1252                                                 text->cursor.row()->previous()->pos(), false);
1253                 if (cur.y() > text->first_y) {
1254                         text->cursorUp(bv_, true);
1255                 }
1256         }
1257         updateScrollbar();
1258 }
1259
1260
1261 void BufferView::Pimpl::cursorNext(LyXText * text)
1262 {
1263         if (!text->cursor.row()->next()) {
1264                 int y = text->cursor.y() - text->cursor.row()->baseline() +
1265                         text->cursor.row()->height();
1266                 if (y > int(text->first_y + workarea_.height())) {
1267                         screen_->draw(bv_->text, bv_,
1268                                                   bv_->text->first_y + workarea_.height());
1269                         updateScrollbar();
1270                 }
1271                 return;
1272         }
1273
1274         int y = text->first_y + workarea_.height();
1275         if (text->inset_owner && !text->first_y) {
1276                 y -= (bv_->text->cursor.iy()
1277                           - bv_->text->first_y
1278                           + bv_->theLockingInset()->insetInInsetY());
1279         }
1280         text->getRowNearY(y);
1281
1282         Row * cursorrow = text->cursor.row();
1283         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1284         finishUndo();
1285         int new_y;
1286         if (cursorrow == bv_->text->cursor.row()) {
1287                 // we have a row which is higher than the workarea so we leave the
1288                 // cursor on the start of the row and move only the draw down as soon
1289                 // as we move the cursor or do something while inside the row (it may
1290                 // span several workarea-heights) we'll move to the top again, but this
1291                 // is better than just jump down and only display part of the row.
1292                 new_y = bv_->text->first_y + workarea_.height();
1293         } else {
1294                 if (text->inset_owner) {
1295                         new_y = bv_->text->cursor.iy()
1296                                 + bv_->theLockingInset()->insetInInsetY()
1297                                 + y - text->cursor.row()->baseline();
1298                 } else {
1299                         new_y =  text->cursor.y() - text->cursor.row()->baseline();
1300                 }
1301         }
1302         screen_->draw(bv_->text, bv_, new_y);
1303         if (text->cursor.row()->next()) {
1304                 LyXCursor cur;
1305                 text->setCursor(bv_, cur, text->cursor.row()->next()->par(),
1306                                                 text->cursor.row()->next()->pos(), false);
1307                 if (cur.y() < int(text->first_y + workarea_.height())) {
1308                         text->cursorDown(bv_, true);
1309                 }
1310         }
1311         updateScrollbar();
1312 }
1313
1314
1315 bool BufferView::Pimpl::available() const
1316 {
1317         if (buffer_ && bv_->text)
1318                 return true;
1319         return false;
1320 }
1321
1322
1323 void BufferView::Pimpl::beforeChange(LyXText * text)
1324 {
1325         toggleSelection();
1326         text->clearSelection();
1327 }
1328
1329
1330 void BufferView::Pimpl::savePosition(unsigned int i)
1331 {
1332         if (i >= saved_positions_num)
1333                 return;
1334         saved_positions[i] = Position(buffer_->fileName(),
1335                                       bv_->text->cursor.par()->id(),
1336                                       bv_->text->cursor.pos());
1337         if (i > 0) {
1338                 ostringstream str;
1339                 str << _("Saved bookmark") << ' ' << i;
1340                 owner_->message(str.str().c_str());
1341         }
1342 }
1343
1344
1345 void BufferView::Pimpl::restorePosition(unsigned int i)
1346 {
1347         if (i >= saved_positions_num)
1348                 return;
1349
1350         string const fname = saved_positions[i].filename;
1351
1352         beforeChange(bv_->text);
1353
1354         if (fname != buffer_->fileName()) {
1355                 Buffer * b = bufferlist.exists(fname) ?
1356                         bufferlist.getBuffer(fname) :
1357                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1358                 if (b != 0) buffer(b);
1359         }
1360
1361         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1362         if (!par)
1363                 return;
1364
1365         bv_->text->setCursor(bv_, par,
1366                              min(par->size(), saved_positions[i].par_pos));
1367
1368         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1369         if (i > 0) {
1370                 ostringstream str;
1371                 str << _("Moved to bookmark") << ' ' << i;
1372                 owner_->message(str.str().c_str());
1373         }
1374 }
1375
1376
1377 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1378 {
1379         if (i >= saved_positions_num)
1380                 return false;
1381
1382         return !saved_positions[i].filename.empty();
1383 }
1384
1385
1386 void BufferView::Pimpl::setState()
1387 {
1388         if (!lyxrc.rtl_support)
1389                 return;
1390
1391         LyXText * text = bv_->getLyXText();
1392         if (text->real_current_font.isRightToLeft()
1393             && !(bv_->theLockingInset()
1394                  && bv_->theLockingInset()->lyxCode()== Inset::ERT_CODE))
1395         {
1396                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1397                         owner_->getIntl()->KeyMapSec();
1398         } else {
1399                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1400                         owner_->getIntl()->KeyMapPrim();
1401         }
1402 }
1403
1404
1405 #if 0
1406 void BufferView::Pimpl::insetSleep()
1407 {
1408         if (bv_->theLockingInset() && !inset_slept) {
1409                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1410                 bv_->theLockingInset()->insetUnlock(bv_);
1411                 inset_slept = true;
1412         }
1413 }
1414
1415
1416 void BufferView::Pimpl::insetWakeup()
1417 {
1418         if (bv_->theLockingInset() && inset_slept) {
1419                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1420                 inset_slept = false;
1421         }
1422 }
1423 #endif
1424
1425
1426 void BufferView::Pimpl::insetUnlock()
1427 {
1428         if (bv_->theLockingInset()) {
1429                 if (!inset_slept)
1430                         bv_->theLockingInset()->insetUnlock(bv_);
1431                 bv_->theLockingInset(0);
1432                 finishUndo();
1433                 inset_slept = false;
1434         }
1435 }
1436
1437
1438 bool BufferView::Pimpl::focus() const
1439 {
1440         return workarea_.hasFocus();
1441 }
1442
1443
1444 void BufferView::Pimpl::focus(bool f)
1445 {
1446         if (f) workarea_.setFocus();
1447 }
1448
1449
1450 bool BufferView::Pimpl::active() const
1451 {
1452         return workarea_.active();
1453 }
1454
1455
1456 bool BufferView::Pimpl::belowMouse() const
1457 {
1458         return workarea_.belowMouse();
1459 }
1460
1461
1462 void BufferView::Pimpl::showCursor()
1463 {
1464         if (screen_.get()) {
1465                 if (bv_->theLockingInset())
1466                         bv_->theLockingInset()->showInsetCursor(bv_);
1467                 else
1468                         screen_->showCursor(bv_->text, bv_);
1469         }
1470 }
1471
1472
1473 void BufferView::Pimpl::hideCursor()
1474 {
1475         if (screen_.get()) {
1476                 if (!bv_->theLockingInset())
1477 //                      bv_->theLockingInset()->hideInsetCursor(bv_);
1478 //              else
1479                         screen_->hideCursor();
1480         }
1481 }
1482
1483
1484 void BufferView::Pimpl::toggleSelection(bool b)
1485 {
1486         if (screen_.get()) {
1487                 if (bv_->theLockingInset())
1488                         bv_->theLockingInset()->toggleSelection(bv_, b);
1489                 screen_->toggleSelection(bv_->text, bv_, b);
1490         }
1491 }
1492
1493
1494 void BufferView::Pimpl::toggleToggle()
1495 {
1496         if (screen_.get())
1497                 screen_->toggleToggle(bv_->text, bv_);
1498 }
1499
1500
1501 void BufferView::Pimpl::center()
1502 {
1503         beforeChange(bv_->text);
1504         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1505                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1506         } else {
1507                 screen_->draw(bv_->text, bv_, 0);
1508         }
1509         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1510         redraw();
1511 }
1512
1513
1514 void BufferView::Pimpl::pasteClipboard(bool asPara)
1515 {
1516         if (!buffer_)
1517                 return;
1518
1519         screen_->hideCursor();
1520         beforeChange(bv_->text);
1521
1522         string const clip(workarea_.getClipboard());
1523
1524         if (clip.empty())
1525                 return;
1526
1527         if (asPara) {
1528                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1529         } else {
1530                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1531         }
1532         bv_->getLyXText()->clearSelection();
1533         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1534 }
1535
1536
1537 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1538 {
1539         workarea_.putClipboard(stuff);
1540 }
1541
1542
1543 /*
1544  * Dispatch functions for actions which can be valid for BufferView->text
1545  * and/or InsetText->text!!!
1546  */
1547
1548
1549 inline
1550 void BufferView::Pimpl::moveCursorUpdate(bool selecting, bool fitcur)
1551 {
1552         LyXText * lt = bv_->getLyXText();
1553
1554         if (selecting || lt->selection.mark()) {
1555                 lt->setSelection(bv_);
1556                 if (lt->bv_owner)
1557                         toggleToggle();
1558                 else
1559                         updateInset(lt->inset_owner, false);
1560         }
1561         if (lt->bv_owner) {
1562                 if (fitcur)
1563                         update(lt, BufferView::SELECT|BufferView::FITCUR);
1564                 else
1565                         update(lt, BufferView::SELECT);
1566                 showCursor();
1567         } else if (bv_->text->status() != LyXText::UNCHANGED) {
1568                 bv_->theLockingInset()->hideInsetCursor(bv_);
1569                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1570                 showCursor();
1571         }
1572
1573         if (!lt->selection.set())
1574                 workarea_.haveSelection(false);
1575
1576         /* ---> Everytime the cursor is moved, show the current font state. */
1577         // should this too me moved out of this func?
1578         //owner->showState();
1579         setState();
1580 }
1581
1582
1583 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1584 {
1585         LyXCursor cursor = bv_->getLyXText()->cursor;
1586         Buffer::inset_iterator it =
1587                 find_if(Buffer::inset_iterator(
1588                         cursor.par(), cursor.pos()),
1589                         buffer_->inset_iterator_end(),
1590                         lyx::compare_memfun(&Inset::lyxCode, code));
1591         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1592 }
1593
1594
1595 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1596 {
1597         string filename = filen;
1598
1599         if (filename.empty()) {
1600                 // Launch a file browser
1601                 string initpath = lyxrc.document_path;
1602
1603                 if (available()) {
1604                         string const trypath = owner_->buffer()->filePath();
1605                         // If directory is writeable, use this as default.
1606                         if (IsDirWriteable(trypath))
1607                                 initpath = trypath;
1608                 }
1609
1610                 FileDialog fileDlg(bv_->owner(),
1611                                    _("Select LyX document to insert"),
1612                         LFUN_FILE_INSERT,
1613                         make_pair(string(_("Documents|#o#O")),
1614                                   string(lyxrc.document_path)),
1615                         make_pair(string(_("Examples|#E#e")),
1616                                   string(AddPath(system_lyxdir, "examples"))));
1617
1618                 FileDialog::Result result =
1619                         fileDlg.Select(initpath,
1620                                        _("*.lyx| LyX Documents (*.lyx)"));
1621
1622                 if (result.first == FileDialog::Later)
1623                         return;
1624
1625                 filename = result.second;
1626
1627                 // check selected filename
1628                 if (filename.empty()) {
1629                         owner_->message(_("Canceled."));
1630                         return;
1631                 }
1632         }
1633
1634         // get absolute path of file and add ".lyx" to the filename if
1635         // necessary
1636         filename = FileSearch(string(), filename, "lyx");
1637
1638         string const disp_fn(MakeDisplayPath(filename));
1639
1640         ostringstream s1;
1641         s1 << _("Inserting document") << ' '
1642            << disp_fn << " ...";
1643         owner_->message(s1.str().c_str());
1644         bool const res = bv_->insertLyXFile(filename);
1645         if (res) {
1646                 ostringstream str;
1647                 str << _("Document") << ' ' << disp_fn
1648                     << ' ' << _("inserted.");
1649                 owner_->message(str.str().c_str());
1650         } else {
1651                 ostringstream str;
1652                 str << _("Could not insert document") << ' '
1653                     << disp_fn;
1654                 owner_->message(str.str().c_str());
1655         }
1656 }
1657
1658
1659 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1660 {
1661         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1662                               << action <<"] arg[" << argument << "]" << endl;
1663
1664         LyXTextClass const & tclass = textclasslist[buffer_->params.textclass];
1665
1666         switch (action) {
1667                 // --- Misc -------------------------------------------
1668         case LFUN_APPENDIX:
1669         {
1670                 if (available()) {
1671                         LyXText * lt = bv_->getLyXText();
1672                         lt->toggleAppendix(bv_);
1673                         update(lt,
1674                                BufferView::SELECT
1675                                | BufferView::FITCUR
1676                                | BufferView::CHANGE);
1677                 }
1678         }
1679         break;
1680
1681         case LFUN_TOC_INSERT:
1682         {
1683                 InsetCommandParams p;
1684                 p.setCmdName("tableofcontents");
1685                 Inset * inset = new InsetTOC(p);
1686                 if (!insertInset(inset, tclass.defaultLayoutName()))
1687                         delete inset;
1688                 break;
1689         }
1690
1691         case LFUN_SCROLL_INSET:
1692                 // this is not handled here as this funktion is only aktive
1693                 // if we have a locking_inset and that one is (or contains)
1694                 // a tabular-inset
1695                 break;
1696
1697         case LFUN_INSET_GRAPHICS:
1698         {
1699                 Inset * new_inset = new InsetGraphics;
1700                 if (!insertInset(new_inset)) {
1701                         delete new_inset;
1702                 } else {
1703                         // this is need because you don't use a inset->Edit()
1704                         updateInset(new_inset, true);
1705                         new_inset->edit(bv_);
1706                 }
1707                 break;
1708         }
1709
1710         case LFUN_PASTE:
1711                 bv_->paste();
1712                 setState();
1713                 break;
1714
1715         case LFUN_PASTESELECTION:
1716         {
1717                 bool asPara = false;
1718                 if (argument == "paragraph")
1719                         asPara = true;
1720                 pasteClipboard(asPara);
1721         }
1722         break;
1723
1724         case LFUN_CUT:
1725                 bv_->cut();
1726                 break;
1727
1728         case LFUN_COPY:
1729                 bv_->copy();
1730                 break;
1731
1732         case LFUN_LAYOUT_COPY:
1733                 bv_->copyEnvironment();
1734                 break;
1735
1736         case LFUN_LAYOUT_PASTE:
1737                 bv_->pasteEnvironment();
1738                 setState();
1739                 break;
1740
1741         case LFUN_GOTOERROR:
1742                 gotoInset(Inset::ERROR_CODE, false);
1743                 break;
1744
1745         case LFUN_GOTONOTE:
1746                 gotoInset(Inset::IGNORE_CODE, false);
1747                 break;
1748
1749         case LFUN_REFERENCE_GOTO:
1750         {
1751                 vector<Inset::Code> tmp;
1752                 tmp.push_back(Inset::LABEL_CODE);
1753                 tmp.push_back(Inset::REF_CODE);
1754                 gotoInset(tmp, true);
1755                 break;
1756         }
1757
1758         case LFUN_HYPHENATION:
1759                 specialChar(InsetSpecialChar::HYPHENATION);
1760                 break;
1761
1762         case LFUN_LIGATURE_BREAK:
1763                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1764                 break;
1765
1766         case LFUN_LDOTS:
1767                 specialChar(InsetSpecialChar::LDOTS);
1768                 break;
1769
1770         case LFUN_END_OF_SENTENCE:
1771                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1772                 break;
1773
1774         case LFUN_MENU_SEPARATOR:
1775                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1776                 break;
1777
1778         case LFUN_HFILL:
1779                 hfill();
1780                 break;
1781
1782         case LFUN_DEPTH_MIN:
1783                 changeDepth(bv_, bv_->getLyXText(), -1);
1784                 break;
1785
1786         case LFUN_DEPTH_PLUS:
1787                 changeDepth(bv_, bv_->getLyXText(), 1);
1788                 break;
1789
1790         case LFUN_FREE:
1791                 owner_->getDialogs()->setUserFreeFont();
1792                 break;
1793
1794         case LFUN_FILE_INSERT:
1795                 MenuInsertLyXFile(argument);
1796                 break;
1797
1798         case LFUN_FILE_INSERT_ASCII_PARA:
1799                 InsertAsciiFile(bv_, argument, true);
1800                 break;
1801
1802         case LFUN_FILE_INSERT_ASCII:
1803                 InsertAsciiFile(bv_, argument, false);
1804                 break;
1805
1806         case LFUN_LAYOUT:
1807         {
1808                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1809                                     << argument << endl;
1810
1811                 // This is not the good solution to the empty argument
1812                 // problem, but it will hopefully suffice for 1.2.0.
1813                 // The correct solution would be to augument the
1814                 // function list/array with information about what
1815                 // functions needs arguments and their type.
1816                 if (argument.empty()) {
1817                         owner_->getLyXFunc()->setErrorMessage(
1818                                 _("LyX function 'layout' needs an argument."));
1819                         break;
1820                 }
1821
1822                 // Derive layout number from given argument (string)
1823                 // and current buffer's textclass (number). */
1824                 bool hasLayout = tclass.hasLayout(argument);
1825                 string layout = argument;
1826
1827                 // If the entry is obsolete, use the new one instead.
1828                 if (hasLayout) {
1829                         string const & obs = tclass[layout].obsoleted_by();
1830                         if (!obs.empty())
1831                                 layout = obs;
1832                 }
1833
1834                 if (!hasLayout) {
1835                         owner_->getLyXFunc()->setErrorMessage(
1836                                 string(N_("Layout ")) + argument +
1837                                 N_(" not known"));
1838                         break;
1839                 }
1840
1841                 bool change_layout = (current_layout != layout);
1842                 LyXText * lt = bv_->getLyXText();
1843                 if (!change_layout && lt->selection.set() &&
1844                         lt->selection.start.par() != lt->selection.end.par())
1845                 {
1846                         Paragraph * spar = lt->selection.start.par();
1847                         Paragraph * epar = lt->selection.end.par()->next();
1848                         while(spar != epar) {
1849                                 if (spar->layout() != current_layout) {
1850                                         change_layout = true;
1851                                         break;
1852                                 }
1853                         }
1854                 }
1855                 if (change_layout) {
1856                         hideCursor();
1857                         current_layout = layout;
1858                         update(lt,
1859                                BufferView::SELECT
1860                                | BufferView::FITCUR);
1861                         lt->setLayout(bv_, layout);
1862                         owner_->setLayout(layout);
1863                         update(lt,
1864                                BufferView::SELECT
1865                                | BufferView::FITCUR
1866                                | BufferView::CHANGE);
1867                         setState();
1868                 }
1869         }
1870         break;
1871
1872         case LFUN_LANGUAGE:
1873                 lang(bv_, argument);
1874                 setState();
1875                 owner_->showState();
1876                 break;
1877
1878         case LFUN_EMPH:
1879                 emph(bv_);
1880                 owner_->showState();
1881                 break;
1882
1883         case LFUN_BOLD:
1884                 bold(bv_);
1885                 owner_->showState();
1886                 break;
1887
1888         case LFUN_NOUN:
1889                 noun(bv_);
1890                 owner_->showState();
1891                 break;
1892
1893         case LFUN_CODE:
1894                 code(bv_);
1895                 owner_->showState();
1896                 break;
1897
1898         case LFUN_SANS:
1899                 sans(bv_);
1900                 owner_->showState();
1901                 break;
1902
1903         case LFUN_ROMAN:
1904                 roman(bv_);
1905                 owner_->showState();
1906                 break;
1907
1908         case LFUN_DEFAULT:
1909                 styleReset(bv_);
1910                 owner_->showState();
1911                 break;
1912
1913         case LFUN_UNDERLINE:
1914                 underline(bv_);
1915                 owner_->showState();
1916                 break;
1917
1918         case LFUN_FONT_SIZE:
1919                 fontSize(bv_, argument);
1920                 owner_->showState();
1921                 break;
1922
1923         case LFUN_FONT_STATE:
1924                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1925                 break;
1926
1927         case LFUN_UPCASE_WORD:
1928         {
1929                 LyXText * lt = bv_->getLyXText();
1930
1931                 update(lt,
1932                        BufferView::SELECT
1933                        | BufferView::FITCUR);
1934                 lt->changeCase(bv_, LyXText::text_uppercase);
1935                 if (lt->inset_owner)
1936                         updateInset(lt->inset_owner, true);
1937                 update(lt,
1938                        BufferView::SELECT
1939                        | BufferView::FITCUR
1940                        | BufferView::CHANGE);
1941         }
1942         break;
1943
1944         case LFUN_LOWCASE_WORD:
1945         {
1946                 LyXText * lt = bv_->getLyXText();
1947
1948                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1949                 lt->changeCase(bv_, LyXText::text_lowercase);
1950                 if (lt->inset_owner)
1951                         updateInset(lt->inset_owner, true);
1952                 update(lt,
1953                        BufferView::SELECT
1954                        | BufferView::FITCUR
1955                        | BufferView::CHANGE);
1956         }
1957         break;
1958
1959         case LFUN_CAPITALIZE_WORD:
1960         {
1961                 LyXText * lt = bv_->getLyXText();
1962
1963                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1964                 lt->changeCase(bv_, LyXText::text_capitalization);
1965                 if (lt->inset_owner)
1966                         updateInset(lt->inset_owner, true);
1967                 update(lt,
1968                        BufferView::SELECT
1969                        | BufferView::FITCUR
1970                        | BufferView::CHANGE);
1971         }
1972         break;
1973
1974         case LFUN_TRANSPOSE_CHARS:
1975         {
1976                 LyXText * lt = bv_->getLyXText();
1977
1978                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1979                 lt->transposeChars(*bv_);
1980                 if (lt->inset_owner)
1981                         updateInset(lt->inset_owner, true);
1982                 update(lt,
1983                        BufferView::SELECT
1984                        | BufferView::FITCUR
1985                        | BufferView::CHANGE);
1986         }
1987         break;
1988
1989
1990         case LFUN_INSERT_LABEL:
1991                 MenuInsertLabel(bv_, argument);
1992                 break;
1993
1994         case LFUN_REF_INSERT:
1995                 if (argument.empty()) {
1996                         InsetCommandParams p("ref");
1997                         owner_->getDialogs()->createRef(p.getAsString());
1998                 } else {
1999                         InsetCommandParams p;
2000                         p.setFromString(argument);
2001
2002                         InsetRef * inset = new InsetRef(p, *buffer_);
2003                         if (!insertInset(inset))
2004                                 delete inset;
2005                         else
2006                                 updateInset(inset, true);
2007                 }
2008                 break;
2009
2010         case LFUN_BOOKMARK_SAVE:
2011                 savePosition(strToUnsignedInt(argument));
2012                 break;
2013
2014         case LFUN_BOOKMARK_GOTO:
2015                 restorePosition(strToUnsignedInt(argument));
2016                 break;
2017
2018         case LFUN_REF_GOTO:
2019         {
2020                 string label(argument);
2021                 if (label.empty()) {
2022                         InsetRef * inset =
2023                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
2024                         if (inset) {
2025                                 label = inset->getContents();
2026                                 savePosition(0);
2027                         }
2028                 }
2029
2030                 if (!label.empty()) {
2031                         //bv_->savePosition(0);
2032                         if (!bv_->gotoLabel(label))
2033                                 Alert::alert(_("Error"),
2034                                            _("Couldn't find this label"),
2035                                            _("in current document."));
2036                 }
2037         }
2038         break;
2039
2040                 // --- Cursor Movements -----------------------------
2041         case LFUN_RIGHT:
2042         {
2043                 LyXText * lt = bv_->getLyXText();
2044
2045                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
2046                 if (!lt->selection.mark())
2047                         beforeChange(lt);
2048                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2049                 if (is_rtl)
2050                         lt->cursorLeft(bv_, false);
2051                 if (lt->cursor.pos() < lt->cursor.par()->size()
2052                     && lt->cursor.par()->isInset(lt->cursor.pos())
2053                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
2054                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
2055                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
2056                         if (is_rtl)
2057                                 tmpinset->edit(bv_, false);
2058                         else
2059                                 tmpinset->edit(bv_);
2060                         break;
2061                 }
2062                 if (!is_rtl)
2063                         lt->cursorRight(bv_, false);
2064                 finishUndo();
2065                 moveCursorUpdate(false);
2066                 owner_->showState();
2067         }
2068         break;
2069
2070         case LFUN_LEFT:
2071         {
2072                 // This is soooo ugly. Isn`t it possible to make
2073                 // it simpler? (Lgb)
2074                 LyXText * lt = bv_->getLyXText();
2075                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
2076                 if (!lt->selection.mark())
2077                         beforeChange(lt);
2078                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2079                 LyXCursor const cur = lt->cursor;
2080                 if (!is_rtl)
2081                         lt->cursorLeft(bv_, false);
2082                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
2083                     lt->cursor.pos() < lt->cursor.par()->size() &&
2084                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
2085                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
2086                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
2087                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
2088                         if (is_rtl)
2089                                 tmpinset->edit(bv_);
2090                         else
2091                                 tmpinset->edit(bv_, false);
2092                         break;
2093                 }
2094                 if  (is_rtl)
2095                         lt->cursorRight(bv_, false);
2096
2097                 finishUndo();
2098                 moveCursorUpdate(false);
2099                 owner_->showState();
2100         }
2101         break;
2102
2103         case LFUN_UP:
2104         {
2105                 LyXText * lt = bv_->getLyXText();
2106
2107                 if (!lt->selection.mark())
2108                         beforeChange(lt);
2109                 update(lt, BufferView::UPDATE);
2110                 lt->cursorUp(bv_);
2111                 finishUndo();
2112                 moveCursorUpdate(false);
2113                 owner_->showState();
2114         }
2115         break;
2116
2117         case LFUN_DOWN:
2118         {
2119                 LyXText * lt = bv_->getLyXText();
2120
2121                 if (!lt->selection.mark())
2122                         beforeChange(lt);
2123                 update(lt, BufferView::UPDATE);
2124                 lt->cursorDown(bv_);
2125                 finishUndo();
2126                 moveCursorUpdate(false);
2127                 owner_->showState();
2128         }
2129         break;
2130
2131         case LFUN_UP_PARAGRAPH:
2132         {
2133                 LyXText * lt = bv_->getLyXText();
2134
2135                 if (!lt->selection.mark())
2136                         beforeChange(lt);
2137                 update(lt, BufferView::UPDATE);
2138                 lt->cursorUpParagraph(bv_);
2139                 finishUndo();
2140                 moveCursorUpdate(false);
2141                 owner_->showState();
2142         }
2143         break;
2144
2145         case LFUN_DOWN_PARAGRAPH:
2146         {
2147                 LyXText * lt = bv_->getLyXText();
2148
2149                 if (!lt->selection.mark())
2150                         beforeChange(lt);
2151                 update(lt, BufferView::UPDATE);
2152                 lt->cursorDownParagraph(bv_);
2153                 finishUndo();
2154                 moveCursorUpdate(false);
2155                 owner_->showState();
2156         }
2157         break;
2158
2159         case LFUN_PRIOR:
2160         {
2161                 LyXText * lt = bv_->getLyXText();
2162
2163                 if (!lt->selection.mark())
2164                         beforeChange(lt);
2165                 update(lt, BufferView::UPDATE);
2166                 cursorPrevious(lt);
2167                 finishUndo();
2168                 moveCursorUpdate(false, false);
2169                 owner_->showState();
2170         }
2171         break;
2172
2173         case LFUN_NEXT:
2174         {
2175                 LyXText * lt = bv_->getLyXText();
2176
2177                 if (!lt->selection.mark())
2178                         beforeChange(lt);
2179                 update(lt, BufferView::UPDATE);
2180                 cursorNext(lt);
2181                 finishUndo();
2182                 moveCursorUpdate(false, false);
2183                 owner_->showState();
2184         }
2185         break;
2186
2187         case LFUN_HOME:
2188         {
2189                 LyXText * lt = bv_->getLyXText();
2190
2191                 if (!lt->selection.mark())
2192                         beforeChange(lt);
2193                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2194                 lt->cursorHome(bv_);
2195                 finishUndo();
2196                 moveCursorUpdate(false);
2197                 owner_->showState();
2198         }
2199         break;
2200
2201         case LFUN_END:
2202         {
2203                 LyXText * lt = bv_->getLyXText();
2204
2205                 if (!lt->selection.mark())
2206                         beforeChange(lt);
2207                 update(lt,
2208                        BufferView::SELECT|BufferView::FITCUR);
2209                 lt->cursorEnd(bv_);
2210                 finishUndo();
2211                 moveCursorUpdate(false);
2212                 owner_->showState();
2213         }
2214         break;
2215
2216         case LFUN_SHIFT_TAB:
2217         case LFUN_TAB:
2218         {
2219                 LyXText * lt = bv_->getLyXText();
2220
2221                 if (!lt->selection.mark())
2222                         beforeChange(lt);
2223                 update(lt,
2224                        BufferView::SELECT|BufferView::FITCUR);
2225                 lt->cursorTab(bv_);
2226                 finishUndo();
2227                 moveCursorUpdate(false);
2228                 owner_->showState();
2229         }
2230         break;
2231
2232         case LFUN_WORDRIGHT:
2233         {
2234                 LyXText * lt = bv_->getLyXText();
2235
2236                 if (!lt->selection.mark())
2237                         beforeChange(lt);
2238                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2239                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2240                         lt->cursorLeftOneWord(bv_);
2241                 else
2242                         lt->cursorRightOneWord(bv_);
2243                 finishUndo();
2244                 moveCursorUpdate(false);
2245                 owner_->showState();
2246         }
2247         break;
2248
2249         case LFUN_WORDLEFT:
2250         {
2251                 LyXText * lt = bv_->getLyXText();
2252
2253                 if (!lt->selection.mark())
2254                         beforeChange(lt);
2255                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2256                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2257                         lt->cursorRightOneWord(bv_);
2258                 else
2259                         lt->cursorLeftOneWord(bv_);
2260                 finishUndo();
2261                 moveCursorUpdate(false);
2262                 owner_->showState();
2263         }
2264         break;
2265
2266         case LFUN_BEGINNINGBUF:
2267         {
2268                 LyXText * lt = bv_->getLyXText();
2269
2270                 if (!lt->selection.mark())
2271                         beforeChange(lt);
2272                 update(lt,
2273                        BufferView::SELECT|BufferView::FITCUR);
2274                 lt->cursorTop(bv_);
2275                 finishUndo();
2276                 moveCursorUpdate(false);
2277                 owner_->showState();
2278         }
2279         break;
2280
2281         case LFUN_ENDBUF:
2282         {
2283                 LyXText * lt = bv_->getLyXText();
2284
2285                 if (!lt->selection.mark())
2286                         beforeChange(lt);
2287                 update(lt,
2288                        BufferView::SELECT|BufferView::FITCUR);
2289                 lt->cursorBottom(bv_);
2290                 finishUndo();
2291                 moveCursorUpdate(false);
2292                 owner_->showState();
2293         }
2294         break;
2295
2296                 /* cursor selection ---------------------------- */
2297         case LFUN_RIGHTSEL:
2298         {
2299                 LyXText * lt = bv_->getLyXText();
2300
2301                 update(lt,
2302                        BufferView::SELECT|BufferView::FITCUR);
2303                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2304                         lt->cursorLeft(bv_);
2305                 else
2306                         lt->cursorRight(bv_);
2307                 finishUndo();
2308                 moveCursorUpdate(true);
2309                 owner_->showState();
2310         }
2311         break;
2312
2313         case LFUN_LEFTSEL:
2314         {
2315                 LyXText * lt = bv_->getLyXText();
2316
2317                 update(lt,
2318                        BufferView::SELECT|BufferView::FITCUR);
2319                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2320                         lt->cursorRight(bv_);
2321                 else
2322                         lt->cursorLeft(bv_);
2323                 finishUndo();
2324                 moveCursorUpdate(true);
2325                 owner_->showState();
2326         }
2327         break;
2328
2329         case LFUN_UPSEL:
2330         {
2331                 LyXText * lt = bv_->getLyXText();
2332
2333                 update(lt,
2334                        BufferView::SELECT|BufferView::FITCUR);
2335                 lt->cursorUp(bv_, true);
2336                 finishUndo();
2337                 moveCursorUpdate(true);
2338                 owner_->showState();
2339         }
2340         break;
2341
2342         case LFUN_DOWNSEL:
2343         {
2344                 LyXText * lt = bv_->getLyXText();
2345
2346                 update(lt,
2347                        BufferView::SELECT|BufferView::FITCUR);
2348                 lt->cursorDown(bv_, true);
2349                 finishUndo();
2350                 moveCursorUpdate(true);
2351                 owner_->showState();
2352         }
2353         break;
2354
2355         case LFUN_UP_PARAGRAPHSEL:
2356         {
2357                 LyXText * lt = bv_->getLyXText();
2358
2359                 update(lt,
2360                        BufferView::SELECT|BufferView::FITCUR);
2361                 lt->cursorUpParagraph(bv_);
2362                 finishUndo();
2363                 moveCursorUpdate(true);
2364                 owner_->showState();
2365         }
2366         break;
2367
2368         case LFUN_DOWN_PARAGRAPHSEL:
2369         {
2370                 LyXText * lt = bv_->getLyXText();
2371
2372                 update(lt,
2373                        BufferView::SELECT|BufferView::FITCUR);
2374                 lt->cursorDownParagraph(bv_);
2375                 finishUndo();
2376                 moveCursorUpdate(true);
2377                 owner_->showState();
2378         }
2379         break;
2380
2381         case LFUN_PRIORSEL:
2382         {
2383                 LyXText * lt = bv_->getLyXText();
2384
2385                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2386                 cursorPrevious(lt);
2387                 finishUndo();
2388                 moveCursorUpdate(true);
2389                 owner_->showState();
2390         }
2391         break;
2392
2393         case LFUN_NEXTSEL:
2394         {
2395                 LyXText * lt = bv_->getLyXText();
2396
2397                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2398                 cursorNext(lt);
2399                 finishUndo();
2400                 moveCursorUpdate(true);
2401                 owner_->showState();
2402         }
2403         break;
2404
2405         case LFUN_HOMESEL:
2406         {
2407                 LyXText * lt = bv_->getLyXText();
2408
2409                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2410                 lt->cursorHome(bv_);
2411                 finishUndo();
2412                 moveCursorUpdate(true);
2413                 owner_->showState();
2414         }
2415         break;
2416
2417         case LFUN_ENDSEL:
2418         {
2419                 LyXText * lt = bv_->getLyXText();
2420
2421                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2422                 lt->cursorEnd(bv_);
2423                 finishUndo();
2424                 moveCursorUpdate(true);
2425                 owner_->showState();
2426         }
2427         break;
2428
2429         case LFUN_WORDRIGHTSEL:
2430         {
2431                 LyXText * lt = bv_->getLyXText();
2432
2433                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2434                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2435                         lt->cursorLeftOneWord(bv_);
2436                 else
2437                         lt->cursorRightOneWord(bv_);
2438                 finishUndo();
2439                 moveCursorUpdate(true);
2440                 owner_->showState();
2441         }
2442         break;
2443
2444         case LFUN_WORDLEFTSEL:
2445         {
2446                 LyXText * lt = bv_->getLyXText();
2447
2448                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2449                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2450                         lt->cursorRightOneWord(bv_);
2451                 else
2452                         lt->cursorLeftOneWord(bv_);
2453                 finishUndo();
2454                 moveCursorUpdate(true);
2455                 owner_->showState();
2456         }
2457         break;
2458
2459         case LFUN_BEGINNINGBUFSEL:
2460         {
2461                 LyXText * lt = bv_->getLyXText();
2462
2463                 if (lt->inset_owner)
2464                         break;
2465                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2466                 lt->cursorTop(bv_);
2467                 finishUndo();
2468                 moveCursorUpdate(true);
2469                 owner_->showState();
2470         }
2471         break;
2472
2473         case LFUN_ENDBUFSEL:
2474         {
2475                 LyXText * lt = bv_->getLyXText();
2476
2477                 if (lt->inset_owner)
2478                         break;
2479                 update(lt,
2480                        BufferView::SELECT|BufferView::FITCUR);
2481                 lt->cursorBottom(bv_);
2482                 finishUndo();
2483                 moveCursorUpdate(true);
2484                 owner_->showState();
2485         }
2486         break;
2487
2488                 // --- text changing commands ------------------------
2489         case LFUN_BREAKLINE:
2490         {
2491                 LyXText * lt = bv_->getLyXText();
2492
2493                 beforeChange(lt);
2494                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2495                 update(lt,
2496                        BufferView::SELECT
2497                        | BufferView::FITCUR
2498                        | BufferView::CHANGE);
2499                 lt->setCursor(bv_, lt->cursor.par(), lt->cursor.pos());
2500                 moveCursorUpdate(false);
2501         }
2502         break;
2503
2504         case LFUN_PROTECTEDSPACE:
2505         {
2506                 LyXText * lt = bv_->getLyXText();
2507
2508                 LyXLayout const & style = tclass[lt->cursor.par()->layout()];
2509
2510                 if (style.free_spacing) {
2511                         lt->insertChar(bv_, ' ');
2512                         update(lt,
2513                                BufferView::SELECT
2514                                | BufferView::FITCUR
2515                                | BufferView::CHANGE);
2516                 } else {
2517                         specialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
2518                 }
2519                 moveCursorUpdate(false);
2520         }
2521         break;
2522
2523         case LFUN_SETMARK:
2524         {
2525                 LyXText * lt = bv_->getLyXText();
2526
2527                 if (lt->selection.mark()) {
2528                         beforeChange(lt);
2529                         update(lt,
2530                                BufferView::SELECT
2531                                | BufferView::FITCUR);
2532                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2533                 } else {
2534                         beforeChange(lt);
2535                         lt->selection.mark(true);
2536                         update(lt,
2537                                BufferView::SELECT
2538                                | BufferView::FITCUR);
2539                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2540                 }
2541                 lt->selection.cursor = lt->cursor;
2542         }
2543         break;
2544
2545         case LFUN_DELETE:
2546         {
2547                 LyXText * lt = bv_->getLyXText();
2548
2549                 if (!lt->selection.set()) {
2550                         lt->Delete(bv_);
2551                         lt->selection.cursor = lt->cursor;
2552                         update(lt,
2553                                BufferView::SELECT
2554                                | BufferView::FITCUR
2555                                | BufferView::CHANGE);
2556                         // It is possible to make it a lot faster still
2557                         // just comment out the line below...
2558                         showCursor();
2559                 } else {
2560                         bv_->cut(false);
2561                 }
2562                 moveCursorUpdate(false);
2563                 owner_->showState();
2564                 setState();
2565         }
2566         break;
2567
2568         case LFUN_DELETE_SKIP:
2569         {
2570                 LyXText * lt = bv_->getLyXText();
2571
2572                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2573
2574                 LyXCursor cursor = lt->cursor;
2575
2576                 if (!lt->selection.set()) {
2577                         if (cursor.pos() == cursor.par()->size()) {
2578                                 lt->cursorRight(bv_);
2579                                 cursor = lt->cursor;
2580                                 if (cursor.pos() == 0
2581                                     && !(cursor.par()->params().spaceTop()
2582                                          == VSpace (VSpace::NONE))) {
2583                                         lt->setParagraph
2584                                                 (bv_,
2585                                                  cursor.par()->params().lineTop(),
2586                                                  cursor.par()->params().lineBottom(),
2587                                                  cursor.par()->params().pagebreakTop(),
2588                                                  cursor.par()->params().pagebreakBottom(),
2589                                                  VSpace(VSpace::NONE),
2590                                                  cursor.par()->params().spaceBottom(),
2591                                                  cursor.par()->params().spacing(),
2592                                                  cursor.par()->params().align(),
2593                                                  cursor.par()->params().labelWidthString(), 0);
2594                                         lt->cursorLeft(bv_);
2595                                         update(lt,
2596                                                BufferView::SELECT
2597                                                | BufferView::FITCUR
2598                                                | BufferView::CHANGE);
2599                                 } else {
2600                                         lt->cursorLeft(bv_);
2601                                         lt->Delete(bv_);
2602                                         lt->selection.cursor = lt->cursor;
2603                                         update(lt,
2604                                                BufferView::SELECT
2605                                                | BufferView::FITCUR
2606                                                | BufferView::CHANGE);
2607                                 }
2608                         } else {
2609                                 lt->Delete(bv_);
2610                                 lt->selection.cursor = lt->cursor;
2611                                 update(lt,
2612                                        BufferView::SELECT
2613                                        | BufferView::FITCUR
2614                                        | BufferView::CHANGE);
2615                         }
2616                 } else {
2617                         bv_->cut(false);
2618                 }
2619         }
2620         break;
2621
2622         /* -------> Delete word forward. */
2623         case LFUN_DELETE_WORD_FORWARD:
2624                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2625                 bv_->getLyXText()->deleteWordForward(bv_);
2626                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2627                 moveCursorUpdate(false);
2628                 owner_->showState();
2629                 break;
2630
2631                 /* -------> Delete word backward. */
2632         case LFUN_DELETE_WORD_BACKWARD:
2633         {
2634                 LyXText * lt = bv_->getLyXText();
2635
2636                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2637                 lt->deleteWordBackward(bv_);
2638                 update(lt,
2639                        BufferView::SELECT
2640                        | BufferView::FITCUR
2641                        | BufferView::CHANGE);
2642                 moveCursorUpdate(false);
2643                 owner_->showState();
2644         }
2645         break;
2646
2647                 /* -------> Kill to end of line. */
2648         case LFUN_DELETE_LINE_FORWARD:
2649         {
2650                 LyXText * lt = bv_->getLyXText();
2651
2652                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2653                 lt->deleteLineForward(bv_);
2654                 update(lt,
2655                        BufferView::SELECT
2656                        | BufferView::FITCUR
2657                        | BufferView::CHANGE);
2658                 moveCursorUpdate(false);
2659         }
2660         break;
2661
2662                 /* -------> Set mark off. */
2663         case LFUN_MARK_OFF:
2664         {
2665                 LyXText * lt = bv_->getLyXText();
2666
2667                 beforeChange(lt);
2668                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2669                 lt->selection.cursor = lt->cursor;
2670                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2671         }
2672         break;
2673
2674                 /* -------> Set mark on. */
2675         case LFUN_MARK_ON:
2676         {
2677                 LyXText * lt = bv_->getLyXText();
2678
2679                 beforeChange(lt);
2680                 lt->selection.mark(true);
2681                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2682                 lt->selection.cursor = lt->cursor;
2683                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2684         }
2685         break;
2686
2687         case LFUN_BACKSPACE:
2688         {
2689                 LyXText * lt = bv_->getLyXText();
2690
2691                 if (!lt->selection.set()) {
2692                         if (owner_->getIntl()->getTrans().backspace()) {
2693                                 lt->backspace(bv_);
2694                                 lt->selection.cursor = lt->cursor;
2695                                 update(lt,
2696                                        BufferView::SELECT
2697                                        | BufferView::FITCUR
2698                                        | BufferView::CHANGE);
2699                                 // It is possible to make it a lot faster still
2700                                 // just comment out the line below...
2701                                 showCursor();
2702                         }
2703                 } else {
2704                         bv_->cut(false);
2705                 }
2706                 owner_->showState();
2707                 setState();
2708         }
2709         break;
2710
2711         case LFUN_BACKSPACE_SKIP:
2712         {
2713                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2714                 LyXText * lt = bv_->getLyXText();
2715
2716                 LyXCursor cursor = lt->cursor;
2717
2718                 if (!lt->selection.set()) {
2719                         if (cursor.pos() == 0
2720                             && !(cursor.par()->params().spaceTop()
2721                                  == VSpace (VSpace::NONE))) {
2722                                 lt->setParagraph
2723                                         (bv_,
2724                                          cursor.par()->params().lineTop(),
2725                                          cursor.par()->params().lineBottom(),
2726                                          cursor.par()->params().pagebreakTop(),
2727                                          cursor.par()->params().pagebreakBottom(),
2728                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2729                                          cursor.par()->params().spacing(),
2730                                          cursor.par()->params().align(),
2731                                          cursor.par()->params().labelWidthString(), 0);
2732                                 update(lt,
2733                                        BufferView::SELECT
2734                                        | BufferView::FITCUR
2735                                        | BufferView::CHANGE);
2736                         } else {
2737                                 lt->backspace(bv_);
2738                                 lt->selection.cursor = cursor;
2739                                 update(lt,
2740                                        BufferView::SELECT
2741                                        | BufferView::FITCUR
2742                                        | BufferView::CHANGE);
2743                         }
2744                 } else
2745                         bv_->cut(false);
2746         }
2747         break;
2748
2749         case LFUN_BREAKPARAGRAPH:
2750         {
2751                 LyXText * lt = bv_->getLyXText();
2752
2753                 beforeChange(lt);
2754                 lt->breakParagraph(bv_, 0);
2755                 update(lt,
2756                        BufferView::SELECT
2757                        | BufferView::FITCUR
2758                        | BufferView::CHANGE);
2759                 lt->selection.cursor = lt->cursor;
2760                 setState();
2761                 owner_->showState();
2762                 break;
2763         }
2764
2765         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2766         {
2767                 LyXText * lt = bv_->getLyXText();
2768
2769                 beforeChange(lt);
2770                 lt->breakParagraph(bv_, 1);
2771                 update(lt,
2772                        BufferView::SELECT
2773                        | BufferView::FITCUR
2774                        | BufferView::CHANGE);
2775                 lt->selection.cursor = lt->cursor;
2776                 setState();
2777                 owner_->showState();
2778                 break;
2779         }
2780
2781         case LFUN_BREAKPARAGRAPH_SKIP:
2782         {
2783                 // When at the beginning of a paragraph, remove
2784                 // indentation and add a "defskip" at the top.
2785                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2786                 LyXText * lt = bv_->getLyXText();
2787
2788                 LyXCursor cursor = lt->cursor;
2789
2790                 beforeChange(lt);
2791                 if (cursor.pos() == 0) {
2792                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2793                                 lt->setParagraph
2794                                         (bv_,
2795                                          cursor.par()->params().lineTop(),
2796                                          cursor.par()->params().lineBottom(),
2797                                          cursor.par()->params().pagebreakTop(),
2798                                          cursor.par()->params().pagebreakBottom(),
2799                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2800                                          cursor.par()->params().spacing(),
2801                                          cursor.par()->params().align(),
2802                                          cursor.par()->params().labelWidthString(), 1);
2803                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2804                         }
2805                 }
2806                 else {
2807                         lt->breakParagraph(bv_, 0);
2808                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2809                 }
2810
2811                 update(lt,
2812                        BufferView::SELECT
2813                        | BufferView::FITCUR
2814                        | BufferView::CHANGE);
2815                 lt->selection.cursor = cursor;
2816                 setState();
2817                 owner_->showState();
2818         }
2819         break;
2820
2821         case LFUN_PARAGRAPH_SPACING:
2822         {
2823                 LyXText * lt = bv_->getLyXText();
2824
2825                 Paragraph * par = lt->cursor.par();
2826                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2827                 float cur_value = 1.0;
2828                 if (cur_spacing == Spacing::Other) {
2829                         cur_value = par->params().spacing().getValue();
2830                 }
2831
2832                 istringstream istr(argument.c_str());
2833
2834                 string tmp;
2835                 istr >> tmp;
2836                 Spacing::Space new_spacing = cur_spacing;
2837                 float new_value = cur_value;
2838                 if (tmp.empty()) {
2839                         lyxerr << "Missing argument to `paragraph-spacing'"
2840                                << endl;
2841                 } else if (tmp == "single") {
2842                         new_spacing = Spacing::Single;
2843                 } else if (tmp == "onehalf") {
2844                         new_spacing = Spacing::Onehalf;
2845                 } else if (tmp == "double") {
2846                         new_spacing = Spacing::Double;
2847                 } else if (tmp == "other") {
2848                         new_spacing = Spacing::Other;
2849                         float tmpval = 0.0;
2850                         istr >> tmpval;
2851                         lyxerr << "new_value = " << tmpval << endl;
2852                         if (tmpval != 0.0)
2853                                 new_value = tmpval;
2854                 } else if (tmp == "default") {
2855                         new_spacing = Spacing::Default;
2856                 } else {
2857                         lyxerr << _("Unknown spacing argument: ")
2858                                << argument << endl;
2859                 }
2860                 if (cur_spacing != new_spacing || cur_value != new_value) {
2861                         par->params().spacing(Spacing(new_spacing, new_value));
2862                         lt->redoParagraph(bv_);
2863                         update(lt,
2864                                BufferView::SELECT
2865                                | BufferView::FITCUR
2866                                | BufferView::CHANGE);
2867                 }
2868         }
2869         break;
2870
2871         case LFUN_INSET_TOGGLE:
2872         {
2873                 LyXText * lt = bv_->getLyXText();
2874                 hideCursor();
2875                 beforeChange(lt);
2876                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2877                 lt->toggleInset(bv_);
2878                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2879                 setState();
2880         }
2881                 break;
2882
2883         case LFUN_QUOTE:
2884                 smartQuote();
2885                 break;
2886
2887         case LFUN_HTMLURL:
2888         case LFUN_URL:
2889         {
2890                 InsetCommandParams p;
2891                 if (action == LFUN_HTMLURL)
2892                         p.setCmdName("htmlurl");
2893                 else
2894                         p.setCmdName("url");
2895                 owner_->getDialogs()->createUrl(p.getAsString());
2896         }
2897         break;
2898
2899         case LFUN_INSERT_URL:
2900         {
2901                 InsetCommandParams p;
2902                 p.setFromString(argument);
2903
2904                 InsetUrl * inset = new InsetUrl(p);
2905                 if (!insertInset(inset))
2906                         delete inset;
2907                 else
2908                         updateInset(inset, true);
2909         }
2910         break;
2911
2912         case LFUN_INSET_ERT:
2913                 insertAndEditInset(new InsetERT(buffer_->params));
2914                 break;
2915
2916         case LFUN_INSET_EXTERNAL:
2917                 insertAndEditInset(new InsetExternal);
2918                 break;
2919
2920         case LFUN_INSET_FOOTNOTE:
2921                 insertAndEditInset(new InsetFoot(buffer_->params));
2922                 break;
2923
2924         case LFUN_INSET_MARGINAL:
2925                 insertAndEditInset(new InsetMarginal(buffer_->params));
2926                 break;
2927
2928         case LFUN_INSET_MINIPAGE:
2929                 insertAndEditInset(new InsetMinipage(buffer_->params));
2930                 break;
2931
2932         case LFUN_INSERT_NOTE:
2933                 insertAndEditInset(new InsetNote(buffer_->params));
2934                 break;
2935
2936         case LFUN_INSET_FLOAT:
2937                 // check if the float type exist
2938                 if (floatList.typeExist(argument)) {
2939                         insertAndEditInset(new InsetFloat(buffer_->params,
2940                                                           argument));
2941                 } else {
2942                         lyxerr << "Non-existent float type: "
2943                                << argument << endl;
2944                 }
2945                 break;
2946
2947         case LFUN_INSET_WIDE_FLOAT:
2948                 // check if the float type exist
2949                 if (floatList.typeExist(argument)) {
2950                         InsetFloat * new_inset =
2951                                 new InsetFloat(buffer_->params, argument);
2952                         new_inset->wide(true);
2953                         insertAndEditInset(new_inset);
2954                 } else {
2955                         lyxerr << "Non-existent float type: "
2956                                << argument << endl;
2957                 }
2958                 break;
2959
2960 #if 0
2961         case LFUN_INSET_LIST:
2962                 insertAndEditInset(new InsetList);
2963                 break;
2964
2965         case LFUN_INSET_THEOREM:
2966                 insertAndEditInset(new InsetTheorem);
2967                 break;
2968 #endif
2969
2970         case LFUN_INSET_CAPTION:
2971         {
2972                 // Do we have a locking inset...
2973                 if (bv_->theLockingInset()) {
2974                         lyxerr << "Locking inset code: "
2975                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2976                         InsetCaption * new_inset =
2977                                 new InsetCaption(buffer_->params);
2978                         new_inset->setOwner(bv_->theLockingInset());
2979                         new_inset->setAutoBreakRows(true);
2980                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2981                         new_inset->setFrameColor(0, LColor::captionframe);
2982                         if (insertInset(new_inset))
2983                                 new_inset->edit(bv_);
2984                         else
2985                                 delete new_inset;
2986                 }
2987         }
2988         break;
2989
2990         case LFUN_INSET_TABULAR:
2991         {
2992                 int r = 2;
2993                 int c = 2;
2994                 if (!argument.empty())
2995                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2996                 InsetTabular * new_inset =
2997                         new InsetTabular(*buffer_, r, c);
2998                 bool const rtl =
2999                         bv_->getLyXText()->real_current_font.isRightToLeft();
3000                 if (!open_new_inset(new_inset, rtl))
3001                         delete new_inset;
3002         }
3003         break;
3004
3005         // --- lyxserver commands ----------------------------
3006
3007         case LFUN_CHARATCURSOR:
3008         {
3009                 pos_type pos = bv_->getLyXText()->cursor.pos();
3010                 if (pos < bv_->getLyXText()->cursor.par()->size())
3011                         owner_->getLyXFunc()->setMessage(
3012                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
3013                 else
3014                         owner_->getLyXFunc()->setMessage("EOF");
3015         }
3016         break;
3017
3018         case LFUN_GETXY:
3019                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
3020                                                  + ' '
3021                                                  + tostr(bv_->getLyXText()->cursor.y()));
3022                 break;
3023
3024         case LFUN_SETXY:
3025         {
3026                 int x = 0;
3027                 int y = 0;
3028                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
3029                         lyxerr << "SETXY: Could not parse coordinates in '"
3030                                << argument << std::endl;
3031                 }
3032                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
3033         }
3034         break;
3035
3036         case LFUN_GETLAYOUT:
3037                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout()));
3038                 break;
3039
3040         case LFUN_GETFONT:
3041         {
3042                 LyXFont & font = bv_->getLyXText()->current_font;
3043                 if (font.shape() == LyXFont::ITALIC_SHAPE)
3044                         owner_->getLyXFunc()->setMessage("E");
3045                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
3046                         owner_->getLyXFunc()->setMessage("N");
3047                 else
3048                         owner_->getLyXFunc()->setMessage("0");
3049
3050         }
3051         break;
3052
3053         // --- accented characters ---------------------------
3054
3055         case LFUN_UMLAUT:
3056         case LFUN_CIRCUMFLEX:
3057         case LFUN_GRAVE:
3058         case LFUN_ACUTE:
3059         case LFUN_TILDE:
3060         case LFUN_CEDILLA:
3061         case LFUN_MACRON:
3062         case LFUN_DOT:
3063         case LFUN_UNDERDOT:
3064         case LFUN_UNDERBAR:
3065         case LFUN_CARON:
3066         case LFUN_SPECIAL_CARON:
3067         case LFUN_BREVE:
3068         case LFUN_TIE:
3069         case LFUN_HUNG_UMLAUT:
3070         case LFUN_CIRCLE:
3071         case LFUN_OGONEK:
3072                 if (argument.empty()) {
3073                         // As always...
3074                         owner_->getLyXFunc()->handleKeyFunc(action);
3075                 } else {
3076                         owner_->getLyXFunc()->handleKeyFunc(action);
3077                         owner_->getIntl()->getTrans()
3078                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
3079                         update(bv_->getLyXText(),
3080                                BufferView::SELECT
3081                                | BufferView::FITCUR
3082                                | BufferView::CHANGE);
3083                 }
3084                 break;
3085
3086         case LFUN_MATH_MACRO:
3087                 mathDispatchMathMacro(bv_, argument);
3088                 break;
3089
3090         case LFUN_MATH_DELIM:
3091                 mathDispatchMathDelim(bv_, argument);
3092                 break;
3093
3094         case LFUN_INSERT_MATRIX:
3095                 mathDispatchInsertMatrix(bv_, argument);
3096                 break;
3097
3098         case LFUN_INSERT_MATH:
3099                 mathDispatchInsertMath(bv_, argument);
3100                 break;
3101
3102         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
3103                 mathDispatchMathImportSelection(bv_, argument);
3104                 break;
3105
3106         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
3107                 mathDispatchMathDisplay(bv_, argument);
3108                 break;
3109
3110         case LFUN_MATH_MODE:             // Open or create an inlined math inset
3111                 mathDispatchMathMode(bv_, argument);
3112                 break;
3113
3114         case LFUN_GREEK:                 // Insert a single greek letter
3115                 mathDispatchGreek(bv_, argument);
3116                 break;
3117
3118         case LFUN_CITATION_INSERT:
3119         {
3120                 InsetCommandParams p;
3121                 p.setFromString(argument);
3122
3123                 InsetCitation * inset = new InsetCitation(p);
3124                 if (!insertInset(inset))
3125                         delete inset;
3126                 else
3127                         updateInset(inset, true);
3128         }
3129         break;
3130
3131         case LFUN_INSERT_BIBTEX:
3132         {
3133                 // ale970405+lasgoutt970425
3134                 // The argument can be up to two tokens separated
3135                 // by a space. The first one is the bibstyle.
3136                 string const db       = token(argument, ' ', 0);
3137                 string const bibstyle = token(argument, ' ', 1);
3138
3139                 InsetCommandParams p("BibTeX", db, bibstyle);
3140                 InsetBibtex * inset = new InsetBibtex(p);
3141
3142                 if (insertInset(inset)) {
3143                         if (argument.empty())
3144                                 inset->edit(bv_);
3145                 } else
3146                         delete inset;
3147         }
3148         break;
3149
3150         // BibTeX data bases
3151         case LFUN_BIBDB_ADD:
3152         {
3153                 InsetBibtex * inset =
3154                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3155                 if (inset) {
3156                         inset->addDatabase(argument);
3157                 }
3158         }
3159         break;
3160
3161         case LFUN_BIBDB_DEL:
3162         {
3163                 InsetBibtex * inset =
3164                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3165                 if (inset) {
3166                         inset->delDatabase(argument);
3167                 }
3168         }
3169         break;
3170
3171         case LFUN_BIBTEX_STYLE:
3172         {
3173                 InsetBibtex * inset =
3174                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3175                 if (inset) {
3176                         inset->setOptions(argument);
3177                 }
3178         }
3179         break;
3180
3181         case LFUN_INDEX_CREATE:
3182         {
3183                 InsetCommandParams p("index");
3184                 if (argument.empty()) {
3185                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3186                         p.setContents(idxstring);
3187                 } else {
3188                         p.setContents(argument);
3189                 }
3190
3191                 owner_->getDialogs()->createIndex(p.getAsString());
3192         }
3193         break;
3194
3195         case LFUN_INDEX_INSERT:
3196         {
3197                 InsetCommandParams p;
3198                 p.setFromString(argument);
3199                 InsetIndex * inset = new InsetIndex(p);
3200
3201                 if (!insertInset(inset))
3202                         delete inset;
3203                 else
3204                         updateInset(inset, true);
3205         }
3206         break;
3207
3208         case LFUN_INDEX_INSERT_LAST:
3209         {
3210                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3211                 if (!idxstring.empty()) {
3212                         owner_->message(_("Word `")
3213                                         + idxstring + _(("' indexed.")));
3214                         InsetCommandParams p("index", idxstring);
3215                         InsetIndex * inset = new InsetIndex(p);
3216
3217                         if (!insertInset(inset))
3218                                 delete inset;
3219                         else
3220                                 updateInset(inset, true);
3221                 }
3222         }
3223         break;
3224
3225         case LFUN_INDEX_PRINT:
3226         {
3227                 InsetCommandParams p("printindex");
3228                 Inset * inset = new InsetPrintIndex(p);
3229                 if (!insertInset(inset, tclass.defaultLayoutName()))
3230                         delete inset;
3231         }
3232         break;
3233
3234         case LFUN_PARENTINSERT:
3235         {
3236                 InsetCommandParams p("lyxparent", argument);
3237                 Inset * inset = new InsetParent(p, *buffer_);
3238                 if (!insertInset(inset, tclass.defaultLayoutName()))
3239                         delete inset;
3240         }
3241
3242         break;
3243
3244         case LFUN_CHILD_INSERT:
3245         {
3246                 InsetInclude::Params p;
3247                 p.cparams.setFromString(argument);
3248                 p.masterFilename_ = buffer_->fileName();
3249
3250                 InsetInclude * inset = new InsetInclude(p);
3251                 if (!insertInset(inset))
3252                         delete inset;
3253                 else {
3254                         updateInset(inset, true);
3255                         bv_->owner()->getDialogs()->showInclude(inset);
3256                 }
3257         }
3258         break;
3259
3260         case LFUN_FLOAT_LIST:
3261                 if (floatList.typeExist(argument)) {
3262                         Inset * inset = new InsetFloatList(argument);
3263                         if (!insertInset(inset, tclass.defaultLayoutName()))
3264                                 delete inset;
3265                 } else {
3266                         lyxerr << "Non-existent float type: "
3267                                << argument << endl;
3268                 }
3269                 break;
3270
3271         case LFUN_THESAURUS_ENTRY:
3272         {
3273                 string arg = argument;
3274
3275                 if (arg.empty()) {
3276                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3277                                                                    false);
3278
3279                         // FIXME
3280                         if (arg.size() > 100 || arg.empty()) {
3281                                 // Get word or selection
3282                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3283                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3284                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3285                         }
3286                 }
3287
3288                 bv_->owner()->getDialogs()->showThesaurus(arg);
3289         }
3290                 break;
3291
3292         case LFUN_SELFINSERT:
3293         {
3294                 if (argument.empty()) break;
3295
3296                 /* Automatically delete the currently selected
3297                  * text and replace it with what is being
3298                  * typed in now. Depends on lyxrc settings
3299                  * "auto_region_delete", which defaults to
3300                  * true (on). */
3301
3302                 LyXText * lt = bv_->getLyXText();
3303
3304                 if (lyxrc.auto_region_delete) {
3305                         if (lt->selection.set()) {
3306                                 lt->cutSelection(bv_, false, false);
3307                                 bv_->update(lt,
3308                                             BufferView::SELECT
3309                                             | BufferView::FITCUR
3310                                             | BufferView::CHANGE);
3311                         }
3312                         workarea_.haveSelection(false);
3313                 }
3314
3315                 beforeChange(lt);
3316                 LyXFont const old_font(lt->real_current_font);
3317
3318                 string::const_iterator cit = argument.begin();
3319                 string::const_iterator end = argument.end();
3320                 for (; cit != end; ++cit) {
3321                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3322                 }
3323
3324                 bv_->update(lt,
3325                             BufferView::SELECT
3326                             | BufferView::FITCUR
3327                             | BufferView::CHANGE);
3328
3329                 lt->selection.cursor = lt->cursor;
3330                 moveCursorUpdate(false);
3331
3332                 // real_current_font.number can change so we need to
3333                 // update the minibuffer
3334                 if (old_font != lt->real_current_font)
3335                         owner_->showState();
3336                 //return string();
3337         }
3338         break;
3339
3340         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3341         {
3342                 time_t now_time_t = time(NULL);
3343                 struct tm * now_tm = localtime(&now_time_t);
3344                 setlocale(LC_TIME, "");
3345                 string arg;
3346                 if (!argument.empty())
3347                         arg = argument;
3348                 else
3349                         arg = lyxrc.date_insert_format;
3350                 char datetmp[32];
3351                 int const datetmp_len =
3352                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3353
3354                 LyXText * lt = bv_->getLyXText();
3355
3356                 for (int i = 0; i < datetmp_len; i++) {
3357                         lt->insertChar(bv_, datetmp[i]);
3358                         update(lt,
3359                                BufferView::SELECT
3360                                | BufferView::FITCUR
3361                                | BufferView::CHANGE);
3362                 }
3363
3364                 lt->selection.cursor = lt->cursor;
3365                 moveCursorUpdate(false);
3366         }
3367         break;
3368
3369         case LFUN_UNKNOWN_ACTION:
3370                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3371                 break;
3372
3373         default:
3374                 return false;
3375         } // end of switch
3376
3377         return true;
3378 }
3379
3380
3381 void BufferView::Pimpl::newline()
3382 {
3383         if (available()) {
3384                 LyXText * lt = bv_->getLyXText();
3385                 hideCursor();
3386                 update(lt,
3387                        BufferView::SELECT
3388                        | BufferView::FITCUR);
3389                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3390                 update(lt,
3391                        BufferView::SELECT
3392                        | BufferView::FITCUR
3393                        | BufferView::CHANGE);
3394         }
3395 }
3396
3397
3398 void BufferView::Pimpl::hfill()
3399 {
3400         if (available()) {
3401                 LyXText * lt = bv_->getLyXText();
3402                 hideCursor();
3403                 update(lt,
3404                        BufferView::SELECT
3405                        | BufferView::FITCUR);
3406                 lt->insertChar(bv_, Paragraph::META_HFILL);
3407                 update(lt,
3408                        BufferView::SELECT
3409                        | BufferView::FITCUR
3410                        | BufferView::CHANGE);
3411         }
3412 }
3413
3414
3415 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3416 {
3417         if (available()) {
3418                 LyXText * lt = bv_->getLyXText();
3419
3420                 hideCursor();
3421                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3422                 InsetSpecialChar * new_inset =
3423                         new InsetSpecialChar(kind);
3424                 if (!insertInset(new_inset))
3425                         delete new_inset;
3426                 else
3427                         updateInset(new_inset, true);
3428         }
3429 }
3430
3431
3432 void BufferView::Pimpl::smartQuote()
3433 {
3434         LyXText const * lt = bv_->getLyXText();
3435         Paragraph const * par = lt->cursor.par();
3436         pos_type pos = lt->cursor.pos();
3437         char c;
3438
3439         if (!pos
3440             || (par->isInset(pos - 1)
3441                 && par->getInset(pos - 1)->isSpace()))
3442                 c = ' ';
3443         else
3444                 c = par->getChar(pos - 1);
3445
3446
3447         hideCursor();
3448
3449         LyXLayout const & style =
3450                 textclasslist[bv_->buffer()->params.textclass][par->layout()];
3451
3452         if (style.pass_thru ||
3453                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3454                 bv_->owner()->getLyXFunc()->dispatch(LFUN_SELFINSERT, "\"");
3455 }
3456
3457
3458 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3459 {
3460         if (insertInset(inset))
3461                 inset->edit(bv_);
3462         else
3463                 delete inset;
3464 }
3465
3466
3467 // Open and lock an updatable inset
3468 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3469 {
3470         LyXText * lt = bv_->getLyXText();
3471
3472         beforeChange(lt);
3473         finishUndo();
3474         if (!insertInset(new_inset)) {
3475                 delete new_inset;
3476                 return false;
3477         }
3478         new_inset->edit(bv_, !behind);
3479         return true;
3480 }
3481
3482
3483 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3484 {
3485         // if we are in a locking inset we should try to insert the
3486         // inset there otherwise this is a illegal function now
3487         if (bv_->theLockingInset()) {
3488                 if (bv_->theLockingInset()->insetAllowed(inset))
3489                     return bv_->theLockingInset()->insertInset(bv_, inset);
3490                 return false;
3491         }
3492
3493         // not quite sure if we want this...
3494         setCursorParUndo(bv_);
3495         freezeUndo();
3496
3497         beforeChange(bv_->text);
3498         if (!lout.empty()) {
3499                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3500                 bv_->text->breakParagraph(bv_);
3501                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3502
3503                 if (bv_->text->cursor.par()->size()) {
3504                         bv_->text->cursorLeft(bv_);
3505
3506                         bv_->text->breakParagraph(bv_);
3507                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3508                 }
3509
3510                 string lres = lout;
3511                 LyXTextClass const & tclass =
3512                         textclasslist[buffer_->params.textclass];
3513                 bool hasLayout = tclass.hasLayout(lres);
3514                 string lay = tclass.defaultLayoutName();
3515
3516                 if (hasLayout != false) {
3517                         // layout found
3518                         lay = lres;
3519                 } else {
3520                         // layout not fount using default
3521                         lay = tclass.defaultLayoutName();
3522                 }
3523
3524                 bv_->text->setLayout(bv_, lay);
3525
3526                 bv_->text->setParagraph(bv_, 0, 0,
3527                                    0, 0,
3528                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3529                                    Spacing(),
3530                                    LYX_ALIGN_LAYOUT,
3531                                    string(),
3532                                    0);
3533                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3534         }
3535
3536         bv_->text->insertInset(bv_, inset);
3537         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3538
3539         unFreezeUndo();
3540         return true;
3541 }
3542
3543
3544 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3545 {
3546         if (!inset || !available())
3547                 return;
3548
3549         // first check for locking insets
3550         if (bv_->theLockingInset()) {
3551                 if (bv_->theLockingInset() == inset) {
3552                         if (bv_->text->updateInset(bv_, inset)) {
3553                                 update();
3554                                 if (mark_dirty) {
3555                                         buffer_->markDirty();
3556                                 }
3557                                 updateScrollbar();
3558                                 return;
3559                         }
3560                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3561                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3562                                 update();
3563                                 if (mark_dirty) {
3564                                         buffer_->markDirty();
3565                                 }
3566                                 updateScrollbar();
3567                                 return;
3568                         }
3569                 }
3570         }
3571
3572         // then check if the inset is a top_level inset (has no owner)
3573         // if yes do the update as always otherwise we have to update the
3574         // toplevel inset where this inset is inside
3575         Inset * tl_inset = inset;
3576         while(tl_inset->owner())
3577                 tl_inset = tl_inset->owner();
3578         hideCursor();
3579         if (tl_inset == inset) {
3580                 update(bv_->text, BufferView::UPDATE);
3581                 if (bv_->text->updateInset(bv_, inset)) {
3582                         if (mark_dirty) {
3583                                 update(bv_->text,
3584                                        BufferView::SELECT
3585                                        | BufferView::FITCUR
3586                                        | BufferView::CHANGE);
3587                         } else {
3588                                 update(bv_->text, SELECT);
3589                         }
3590                         return;
3591                 }
3592         } else if (static_cast<UpdatableInset *>(tl_inset)
3593                            ->updateInsetInInset(bv_, inset))
3594         {
3595                         if (bv_->text->updateInset(bv_,  tl_inset)) {
3596                                 update();
3597                                 updateScrollbar();
3598                         }
3599         }
3600 }
3601
3602
3603 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3604                                   bool same_content)
3605 {
3606         if (!available()) return;
3607
3608         hideCursor();
3609         beforeChange(bv_->text);
3610         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3611
3612         LyXCursor const & cursor = bv_->text->cursor;
3613
3614         string contents;
3615         if (same_content &&
3616             cursor.par()->isInset(cursor.pos())) {
3617                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3618                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3619                     != codes.end())
3620                         contents =
3621                                 static_cast<InsetCommand const *>(inset)->getContents();
3622         }
3623
3624
3625         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3626                 if (bv_->text->cursor.pos()
3627                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3628                         LyXCursor tmp = bv_->text->cursor;
3629                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3630                         bv_->text->cursor.pos(0);
3631                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3632                                 bv_->text->cursor = tmp;
3633                                 bv_->owner()->message(_("No more insets"));
3634                         }
3635                 } else {
3636                         bv_->owner()->message(_("No more insets"));
3637                 }
3638         }
3639         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3640         bv_->text->selection.cursor = bv_->text->cursor;
3641 }
3642
3643
3644 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3645 {
3646         gotoInset(vector<Inset::Code>(1, code), same_content);
3647 }