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