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