]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
3f156cfa73cefab542c66090e5fea4fd96822e27
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
28 #include "factory.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
32 #include "gettext.h"
33 #include "intl.h"
34 #include "insetiterator.h"
35 #include "language.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
38 #include "lyx_main.h"
39 #include "lyxfind.h"
40 #include "lyxfunc.h"
41 #include "lyxlayout.h"
42 #include "lyxtext.h"
43 #include "lyxtextclass.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "texrow.h"
51 #include "toc.h"
52 #include "undo.h"
53 #include "vspace.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
61
62 #include "frontends/Alert.h"
63 #include "frontends/Application.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/font_metrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/filefilterlist.h"
71 #include "support/filetools.h"
72 #include "support/package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81
82 using lyx::docstring;
83 using lyx::pos_type;
84
85 using lyx::support::addPath;
86 using lyx::support::bformat;
87 using lyx::support::FileFilterList;
88 using lyx::support::fileSearch;
89 using lyx::support::isDirWriteable;
90 using lyx::support::makeDisplayPath;
91 using lyx::support::makeAbsPath;
92 using lyx::support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::find;
98 using std::make_pair;
99 using std::min;
100 using std::max;
101 using std::mem_fun_ref;
102 using std::string;
103 using std::vector;
104
105
106 namespace {
107
108 unsigned int const saved_positions_num = 20;
109
110
111 /// Return an inset of this class if it exists at the current cursor position
112 template <class T>
113 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
114 {
115         T * inset = 0;
116         DocIterator it = cur;
117         if (it.nextInset() &&
118             it.nextInset()->lyxCode() == code) {
119                 inset = static_cast<T*>(it.nextInset());
120         }
121         return inset;
122 }
123
124 } // anon namespace
125
126
127 BufferView::BufferView()
128         : buffer_(0), wh_(0),
129           cursor_(*this),
130           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
131           intl_(new Intl)
132 {
133         xsel_cache_.set = false;
134
135         saved_positions.resize(saved_positions_num);
136         // load saved bookmarks
137         lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
138         for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
139                 bm != bmList.end(); ++bm)
140                 if (bm->get<0>() < saved_positions_num)
141                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
142         // and then clear them
143         bmList.clear();
144
145         intl_->initKeyMapper(lyxrc.use_kbmap);
146 }
147
148
149 BufferView::~BufferView()
150 {
151 }
152
153
154 Buffer * BufferView::buffer() const
155 {
156         return buffer_;
157 }
158
159
160 void BufferView::setBuffer(Buffer * b)
161 {
162         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
163                             << "[ b = " << b << "]" << endl;
164
165         if (buffer_) {
166                 // Save the actual cursor position and anchor inside the
167                 // buffer so that it can be restored in case we rechange
168                 // to this buffer later on.
169                 buffer_->saveCursor(cursor_.selectionBegin(),
170                                     cursor_.selectionEnd());
171                 // current buffer is going to be switched-off, save cursor pos
172                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
173                         boost::tie(cursor_.pit(), cursor_.pos()) );
174         }
175
176         // If we're quitting lyx, don't bother updating stuff
177         if (quitting) {
178                 buffer_ = 0;
179                 return;
180         }
181
182         // If we are closing current buffer, switch to the first in
183         // buffer list.
184         if (!b) {
185                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
186                                     << " No Buffer!" << endl;
187                 // We are closing the buffer, use the first buffer as current
188                 buffer_ = theApp->bufferList().first();
189         } else {
190                 // Set current buffer
191                 buffer_ = b;
192         }
193
194         // Reset old cursor
195         cursor_ = LCursor(*this);
196         anchor_ref_ = 0;
197         offset_ref_ = 0;
198
199         if (buffer_) {
200                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
201                                     << "Buffer addr: " << buffer_ << endl;
202                 cursor_.push(buffer_->inset());
203                 cursor_.resetAnchor();
204                 buffer_->text().init(this);
205                 buffer_->text().setCurrentFont(cursor_);
206                 if (buffer_->getCursor().size() > 0 &&
207                     buffer_->getAnchor().size() > 0)
208                 {
209                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
210                         cursor_.resetAnchor();
211                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
212                         cursor_.setSelection();
213                 }
214         }
215
216         update();
217
218         if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
219                 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
220 }
221
222
223 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
224 {
225         // Get absolute path of file and add ".lyx"
226         // to the filename if necessary
227         string s = fileSearch(string(), filename, "lyx");
228
229         bool const found = !s.empty();
230
231         if (!found)
232                 s = filename;
233
234         // File already open?
235         if (theApp->bufferList().exists(s)) {
236                 docstring const file = makeDisplayPath(s, 20);
237                 docstring text = bformat(_("The document %1$s is already "
238                                                      "loaded.\n\nDo you want to revert "
239                                                      "to the saved version?"), file);
240                 int const ret = Alert::prompt(_("Revert to saved document?"),
241                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
242
243                 if (ret != 0) {
244                         setBuffer(theApp->bufferList().getBuffer(s));
245                         return true;
246                 }
247                 // FIXME: should be LFUN_REVERT
248                 if (!theApp->bufferList().close(theApp->bufferList().getBuffer(s), false))
249                         return false;
250                 // Fall through to new load. (Asger)
251         }
252
253         Buffer * b = 0;
254
255         if (found) {
256                 b = theApp->bufferList().newBuffer(s);
257                 if (!::loadLyXFile(b, s)) {
258                         theApp->bufferList().release(b);
259                         return false;
260                 }
261         } else {
262                 docstring text = bformat(_("The document %1$s does not yet "
263                                                      "exist.\n\nDo you want to create "
264                                                      "a new document?"), lyx::from_utf8(s));
265                 int const ret = Alert::prompt(_("Create new document?"),
266                          text, 0, 1, _("&Create"), _("Cancel"));
267
268                 if (ret == 0) {
269                         b = newFile(s, string(), true);
270                         if (!b)
271                                 return false;
272                 } else
273                         return false;
274         }
275
276         setBuffer(b);
277         // Send the "errors" signal in case of parsing errors
278         b->errors("Parse");
279
280         // scroll to the position when the file was last closed
281         if (lyxrc.use_lastfilepos) {
282                 lyx::pit_type pit;
283                 lyx::pos_type pos;
284                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
285                 // I am not sure how to separate the following part to a function
286                 // so I will leave this to Lars.
287                 //
288                 // check pit since the document may be externally changed.
289                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
290                         ParIterator it = b->par_iterator_begin();
291                         ParIterator const end = b->par_iterator_end();
292                         for (; it != end; ++it)
293                                 if (it.pit() == pit) {
294                                         // restored pos may be bigger than it->size
295                                         setCursor(makeDocIterator(it, min(pos, it->size())));
296                                         update(Update::FitCursor);
297                                         break;
298                                 }
299                 }
300         }
301
302         if (tolastfiles)
303                 LyX::ref().session().addLastFile(b->fileName());
304
305         return true;
306 }
307
308
309 void BufferView::reload()
310 {
311         string const fn = buffer_->fileName();
312         if (theApp->bufferList().close(buffer_, false))
313                 loadLyXFile(fn);
314 }
315
316
317 void BufferView::resize()
318 {
319         if (!buffer_)
320                 return;
321
322         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
323
324         buffer_->text().init(this);
325         update();
326         switchKeyMap();
327 }
328
329
330 bool BufferView::fitCursor()
331 {
332         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
333                 LyXFont const font = cursor_.getFont();
334                 int const asc = font_metrics::maxAscent(font);
335                 int const des = font_metrics::maxDescent(font);
336                 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
337                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
338                         return false;
339         }
340         center();
341         return true;
342 }
343
344
345 bool BufferView::multiParSel()
346 {
347         if (!cursor_.selection())
348                 return false;
349         bool ret = multiparsel_cache_;
350         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
351         // Either this, or previous selection spans paragraphs
352         return ret || multiparsel_cache_;
353 }
354
355
356 bool BufferView::update(Update::flags flags)
357 {
358         // This is close to a hot-path.
359         if (lyxerr.debugging(Debug::DEBUG)) {
360                 lyxerr[Debug::DEBUG]
361                         << BOOST_CURRENT_FUNCTION
362                         << "[fitcursor = " << (flags & Update::FitCursor)
363                         << ", forceupdate = " << (flags & Update::Force)
364                         << ", singlepar = " << (flags & Update::SinglePar)
365                         << "]  buffer: " << buffer_ << endl;
366         }
367
368         // Check needed to survive LyX startup
369         if (!buffer_)
370                 return false;
371
372         // Update macro store
373         buffer_->buildMacros();
374
375         // First drawing step
376         updateMetrics(flags & Update::SinglePar);
377
378         // The second drawing step is done in WorkArea::redraw() if needed.
379         bool const need_second_step =
380                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
381                 && (fitCursor() || multiParSel());
382
383         return need_second_step;
384 }
385
386
387 void BufferView::updateScrollbar()
388 {
389         if (!buffer_) {
390                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
391                                      << " no text in updateScrollbar" << endl;
392                 scrollbarParameters_.reset();
393                 return;
394         }
395
396         LyXText & t = buffer_->text();
397         int const parsize = int(t.paragraphs().size() - 1);
398         if (anchor_ref_ >  parsize)  {
399                 anchor_ref_ = parsize;
400                 offset_ref_ = 0;
401         }
402
403         lyxerr[Debug::GUI]
404                 << BOOST_CURRENT_FUNCTION
405                 << " Updating scrollbar: height: " << t.paragraphs().size()
406                 << " curr par: " << cursor_.bottom().pit()
407                 << " default height " << defaultRowHeight() << endl;
408
409         // It would be better to fix the scrollbar to understand
410         // values in [0..1] and divide everything by wh
411
412         // estimated average paragraph height:
413         if (wh_ == 0)
414                 wh_ = height_ / 4;
415         int h = t.getPar(anchor_ref_).height();
416
417         // Normalize anchor/offset (MV):
418         while (offset_ref_ > h && anchor_ref_ < parsize) {
419                 anchor_ref_++;
420                 offset_ref_ -= h;
421                 h = t.getPar(anchor_ref_).height();
422         }
423         // Look at paragraph heights on-screen
424         int sumh = 0;
425         int nh = 0;
426         for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
427                 if (sumh > height_)
428                         break;
429                 int const h2 = t.getPar(pit).height();
430                 sumh += h2;
431                 nh++;
432         }
433         int const hav = sumh / nh;
434         // More realistic average paragraph height
435         if (hav > wh_)
436                 wh_ = hav;
437
438         scrollbarParameters_.height = (parsize + 1) * wh_;
439         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
440         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
441 }
442
443
444 ScrollbarParameters const & BufferView::scrollbarParameters() const
445 {
446         return scrollbarParameters_;
447 }
448
449
450 void BufferView::scrollDocView(int value)
451 {
452         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
453                            << "[ value = " << value << "]" << endl;
454
455         if (!buffer_)
456                 return;
457
458         LyXText & t = buffer_->text();
459
460         float const bar = value / float(wh_ * t.paragraphs().size());
461
462         anchor_ref_ = int(bar * t.paragraphs().size());
463         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
464                 anchor_ref_ = int(t.paragraphs().size()) - 1;
465         t.redoParagraph(anchor_ref_);
466         int const h = t.getPar(anchor_ref_).height();
467         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
468 }
469
470
471 void BufferView::setCursorFromScrollbar()
472 {
473         LyXText & t = buffer_->text();
474
475         int const height = 2 * defaultRowHeight();
476         int const first = height;
477         int const last = height_ - height;
478         LCursor & cur = cursor_;
479
480         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
481
482         switch (st) {
483         case bv_funcs::CUR_ABOVE:
484                 t.setCursorFromCoordinates(cur, 0, first);
485                 cur.clearSelection();
486                 break;
487         case bv_funcs::CUR_BELOW:
488                 t.setCursorFromCoordinates(cur, 0, last);
489                 cur.clearSelection();
490                 break;
491         case bv_funcs::CUR_INSIDE:
492                 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
493                 int const newy = min(last, max(y, first));
494                 if (y != newy) {
495                         cur.reset(buffer_->inset());
496                         t.setCursorFromCoordinates(cur, 0, newy);
497                 }
498         }
499 }
500
501
502 Change const BufferView::getCurrentChange()
503 {
504         if (!buffer_->params().tracking_changes || !cursor_.selection())
505                 return Change(Change::UNCHANGED);
506
507         DocIterator dit = cursor_.selectionBegin();
508         return dit.paragraph().lookupChange(dit.pos());
509 }
510
511
512 void BufferView::savePosition(unsigned int i)
513 {
514         if (i >= saved_positions_num)
515                 return;
516         BOOST_ASSERT(cursor_.inTexted());
517         saved_positions[i] = Position(buffer_->fileName(),
518                                       cursor_.paragraph().id(),
519                                       cursor_.pos());
520         if (i > 0)
521                 // emit message signal.
522                 message(bformat(_("Saved bookmark %1$d"), i));
523 }
524
525
526 void BufferView::restorePosition(unsigned int i)
527 {
528         if (i >= saved_positions_num)
529                 return;
530
531         string const fname = saved_positions[i].filename;
532
533         cursor_.clearSelection();
534
535         if (fname != buffer_->fileName()) {
536                 Buffer * b = 0;
537                 if (theApp->bufferList().exists(fname))
538                         b = theApp->bufferList().getBuffer(fname);
539                 else {
540                         b = theApp->bufferList().newBuffer(fname);
541                         // Don't ask, just load it
542                         ::loadLyXFile(b, fname);
543                 }
544                 if (b)
545                         setBuffer(b);
546         }
547
548         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
549         if (par == buffer_->par_iterator_end())
550                 return;
551
552         setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
553
554         if (i > 0)
555                 // emit message signal.
556                 message(bformat(_("Moved to bookmark %1$d"), i));
557 }
558
559
560 bool BufferView::isSavedPosition(unsigned int i)
561 {
562         return i < saved_positions_num && !saved_positions[i].filename.empty();
563 }
564
565 void BufferView::saveSavedPositions()
566 {
567         // save bookmarks. It is better to use the pit interface
568         // but I do not know how to effectively convert between
569         // par_id and pit.
570         for (unsigned int i=1; i < saved_positions_num; ++i) {
571                 if ( isSavedPosition(i) )
572                         LyX::ref().session().saveBookmark( boost::tie(
573                                 i,
574                                 saved_positions[i].filename,
575                                 saved_positions[i].par_id,
576                                 saved_positions[i].par_pos) );
577         }
578 }
579
580 void BufferView::switchKeyMap()
581 {
582         if (!lyxrc.rtl_support)
583                 return;
584
585         if (getLyXText()->real_current_font.isRightToLeft()) {
586                 if (intl_->keymap == Intl::PRIMARY)
587                         intl_->keyMapSec();
588         } else {
589                 if (intl_->keymap == Intl::SECONDARY)
590                         intl_->keyMapPrim();
591         }
592 }
593
594
595 int BufferView::workWidth() const
596 {
597         return width_;
598 }
599
600
601 void BufferView::center()
602 {
603         CursorSlice & bot = cursor_.bottom();
604         lyx::pit_type const pit = bot.pit();
605         bot.text()->redoParagraph(pit);
606         Paragraph const & par = bot.text()->paragraphs()[pit];
607         anchor_ref_ = pit;
608         offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
609                 + par.ascent() - height_ / 2;
610 }
611
612
613 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
614 {
615         FuncStatus flag;
616
617         switch (cmd.action) {
618
619         case LFUN_UNDO:
620                 flag.enabled(!buffer_->undostack().empty());
621                 break;
622         case LFUN_REDO:
623                 flag.enabled(!buffer_->redostack().empty());
624                 break;
625         case LFUN_FILE_INSERT:
626         case LFUN_FILE_INSERT_ASCII_PARA:
627         case LFUN_FILE_INSERT_ASCII:
628         case LFUN_BOOKMARK_SAVE:
629                 // FIXME: Actually, these LFUNS should be moved to LyXText
630                 flag.enabled(cursor_.inTexted());
631                 break;
632         case LFUN_FONT_STATE:
633         case LFUN_LABEL_INSERT:
634         case LFUN_PARAGRAPH_GOTO:
635         // FIXME handle non-trivially
636         case LFUN_OUTLINE_UP:
637         case LFUN_OUTLINE_DOWN:
638         case LFUN_OUTLINE_IN:
639         case LFUN_OUTLINE_OUT:
640         case LFUN_NOTE_NEXT:
641         case LFUN_REFERENCE_NEXT:
642         case LFUN_WORD_FIND:
643         case LFUN_WORD_REPLACE:
644         case LFUN_MARK_OFF:
645         case LFUN_MARK_ON:
646         case LFUN_MARK_TOGGLE:
647         case LFUN_SCREEN_RECENTER:
648         case LFUN_BIBTEX_DATABASE_ADD:
649         case LFUN_BIBTEX_DATABASE_DEL:
650         case LFUN_WORDS_COUNT:
651         case LFUN_NEXT_INSET_TOGGLE:
652                 flag.enabled(true);
653                 break;
654
655         case LFUN_LABEL_GOTO: {
656                 flag.enabled(!cmd.argument().empty()
657                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
658                 break;
659         }
660
661         case LFUN_BOOKMARK_GOTO:
662                 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
663                 break;
664
665         case LFUN_CHANGES_TRACK:
666                 flag.enabled(true);
667                 flag.setOnOff(buffer_->params().tracking_changes);
668                 break;
669
670         case LFUN_CHANGES_OUTPUT: {
671                 OutputParams runparams;
672                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
673                 flag.enabled(buffer_ && buffer_->params().tracking_changes
674                         && features.isAvailable("dvipost"));
675                 flag.setOnOff(buffer_->params().output_changes);
676                 break;
677         }
678
679         case LFUN_CHANGES_MERGE:
680         case LFUN_CHANGE_NEXT:
681         case LFUN_ALL_CHANGES_ACCEPT:
682         case LFUN_ALL_CHANGES_REJECT:
683                 flag.enabled(buffer_ && buffer_->params().tracking_changes);
684                 break;
685
686         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
687                 flag.setOnOff(buffer_->params().compressed);
688                 break;
689         }
690
691         default:
692                 flag.enabled(false);
693         }
694
695         return flag;
696 }
697
698
699 bool BufferView::dispatch(FuncRequest const & cmd)
700 {
701         //lyxerr << BOOST_CURRENT_FUNCTION
702         //       << [ cmd = " << cmd << "]" << endl;
703
704         // Make sure that the cached BufferView is correct.
705         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
706                 << " action[" << cmd.action << ']'
707                 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
708                 << " x[" << cmd.x << ']'
709                 << " y[" << cmd.y << ']'
710                 << " button[" << cmd.button() << ']'
711                 << endl;
712
713         LCursor & cur = cursor_;
714
715         switch (cmd.action) {
716
717         case LFUN_UNDO:
718                 if (buffer_) {
719                         cur.message(_("Undo"));
720                         cur.clearSelection();
721                         if (!textUndo(*this))
722                                 cur.message(_("No further undo information"));
723                         update();
724                         switchKeyMap();
725                 }
726                 break;
727
728         case LFUN_REDO:
729                 if (buffer_) {
730                         cur.message(_("Redo"));
731                         cur.clearSelection();
732                         if (!textRedo(*this))
733                                 cur.message(_("No further redo information"));
734                         update();
735                         switchKeyMap();
736                 }
737                 break;
738
739         case LFUN_FILE_INSERT:
740                 // FIXME: We don't know the encoding of filenames
741                 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
742                 break;
743
744         case LFUN_FILE_INSERT_ASCII_PARA:
745                 // FIXME: We don't know the encoding of filenames
746                 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
747                 break;
748
749         case LFUN_FILE_INSERT_ASCII:
750                 // FIXME: We don't know the encoding of filenames
751                 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
752                 break;
753
754         case LFUN_FONT_STATE:
755                 cur.message(lyx::from_utf8(cur.currentState()));
756                 break;
757
758         case LFUN_BOOKMARK_SAVE:
759                 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
760                 break;
761
762         case LFUN_BOOKMARK_GOTO:
763                 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
764                 break;
765
766         case LFUN_LABEL_GOTO: {
767                 string label = lyx::to_utf8(cmd.argument());
768                 if (label.empty()) {
769                         InsetRef * inset =
770                                 getInsetByCode<InsetRef>(cursor_,
771                                                          InsetBase::REF_CODE);
772                         if (inset) {
773                                 label = inset->getContents();
774                                 savePosition(0);
775                         }
776                 }
777
778                 if (!label.empty())
779                         gotoLabel(label);
780                 break;
781         }
782
783         case LFUN_PARAGRAPH_GOTO: {
784                 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
785                 ParIterator par = buffer_->getParFromID(id);
786                 if (par == buffer_->par_iterator_end()) {
787                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
788                                             << id << ']' << endl;
789                         break;
790                 } else {
791                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
792                                             << " found." << endl;
793                 }
794
795                 // Set the cursor
796                 setCursor(makeDocIterator(par, 0));
797
798                 update();
799                 switchKeyMap();
800                 break;
801         }
802
803         case LFUN_OUTLINE_UP:
804                 lyx::toc::outline(lyx::toc::Up, cursor_);
805                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
806                 updateLabels(*buffer_);
807                 break;
808         case LFUN_OUTLINE_DOWN:
809                 lyx::toc::outline(lyx::toc::Down, cursor_);
810                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
811                 updateLabels(*buffer_);
812                 break;
813         case LFUN_OUTLINE_IN:
814                 lyx::toc::outline(lyx::toc::In, cursor_);
815                 updateLabels(*buffer_);
816                 break;
817         case LFUN_OUTLINE_OUT:
818                 lyx::toc::outline(lyx::toc::Out, cursor_);
819                 updateLabels(*buffer_);
820                 break;
821
822         case LFUN_NOTE_NEXT:
823                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
824                 break;
825
826         case LFUN_REFERENCE_NEXT: {
827                 vector<InsetBase_code> tmp;
828                 tmp.push_back(InsetBase::LABEL_CODE);
829                 tmp.push_back(InsetBase::REF_CODE);
830                 bv_funcs::gotoInset(this, tmp, true);
831                 break;
832         }
833
834         case LFUN_CHANGES_TRACK:
835                 trackChanges();
836                 break;
837
838         case LFUN_CHANGES_OUTPUT: {
839                 bool const state = buffer_->params().output_changes;
840                 buffer_->params().output_changes = !state;
841                 break;
842         }
843
844         case LFUN_CHANGE_NEXT:
845                 lyx::find::findNextChange(this);
846                 break;
847
848         case LFUN_CHANGES_MERGE:
849                 if (lyx::find::findNextChange(this))
850                         showDialog("changes");
851                 break;
852
853         case LFUN_ALL_CHANGES_ACCEPT: {
854                 cursor_.reset(buffer_->inset());
855 #ifdef WITH_WARNINGS
856 #warning FIXME changes
857 #endif
858                 while (lyx::find::findNextChange(this))
859                         getLyXText()->acceptChange(cursor_);
860                 update();
861                 break;
862         }
863
864         case LFUN_ALL_CHANGES_REJECT: {
865                 cursor_.reset(buffer_->inset());
866 #ifdef WITH_WARNINGS
867 #warning FIXME changes
868 #endif
869                 while (lyx::find::findNextChange(this))
870                         getLyXText()->rejectChange(cursor_);
871                 break;
872         }
873
874         case LFUN_WORD_FIND:
875                 lyx::find::find(this, cmd);
876                 break;
877
878         case LFUN_WORD_REPLACE:
879                 lyx::find::replace(this, cmd);
880                 break;
881
882         case LFUN_MARK_OFF:
883                 cur.clearSelection();
884                 cur.resetAnchor();
885                 cur.message(lyx::from_utf8(N_("Mark off")));
886                 break;
887
888         case LFUN_MARK_ON:
889                 cur.clearSelection();
890                 cur.mark() = true;
891                 cur.resetAnchor();
892                 cur.message(lyx::from_utf8(N_("Mark on")));
893                 break;
894
895         case LFUN_MARK_TOGGLE:
896                 cur.clearSelection();
897                 if (cur.mark()) {
898                         cur.mark() = false;
899                         cur.message(lyx::from_utf8(N_("Mark removed")));
900                 } else {
901                         cur.mark() = true;
902                         cur.message(lyx::from_utf8(N_("Mark set")));
903                 }
904                 cur.resetAnchor();
905                 break;
906
907         case LFUN_SCREEN_RECENTER:
908                 center();
909                 break;
910
911         case LFUN_BIBTEX_DATABASE_ADD: {
912                 LCursor tmpcur = cursor_;
913                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
914                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
915                                                 InsetBase::BIBTEX_CODE);
916                 if (inset) {
917                         if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
918                                 buffer_->updateBibfilesCache();
919                 }
920                 break;
921         }
922
923         case LFUN_BIBTEX_DATABASE_DEL: {
924                 LCursor tmpcur = cursor_;
925                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
926                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
927                                                 InsetBase::BIBTEX_CODE);
928                 if (inset) {
929                         if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
930                                 buffer_->updateBibfilesCache();
931                 }
932                 break;
933         }
934
935         case LFUN_WORDS_COUNT: {
936                 DocIterator from, to;
937                 if (cur.selection()) {
938                         from = cur.selectionBegin();
939                         to = cur.selectionEnd();
940                 } else {
941                         from = doc_iterator_begin(buffer_->inset());
942                         to = doc_iterator_end(buffer_->inset());
943                 }
944                 int const count = countWords(from, to);
945                 docstring message;
946                 if (count != 1) {
947                         if (cur.selection())
948                                 message = bformat(_("%1$d words in selection."),
949                                           count);
950                                 else
951                                         message = bformat(_("%1$d words in document."),
952                                                           count);
953                 }
954                 else {
955                         if (cur.selection())
956                                 message = _("One word in selection.");
957                         else
958                                 message = _("One word in document.");
959                 }
960
961                 Alert::information(_("Count words"), message);
962         }
963                 break;
964
965         case LFUN_BUFFER_TOGGLE_COMPRESSION:
966                 // turn compression on/off
967                 buffer_->params().compressed = !buffer_->params().compressed;
968                 break;
969
970         case LFUN_NEXT_INSET_TOGGLE: {
971                 // this is the real function we want to invoke
972                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
973                 // if there is an inset at cursor, see whether it
974                 // wants to toggle.
975                 InsetBase * inset = cur.nextInset();
976                 if (inset && inset->isActive()) {
977                         LCursor tmpcur = cur;
978                         tmpcur.pushLeft(*inset);
979                         inset->dispatch(tmpcur, tmpcmd);
980                         if (tmpcur.result().dispatched()) {
981                                 cur.dispatched();
982                         }
983                 }
984                 // if it did not work, try the underlying inset.
985                 if (!cur.result().dispatched())
986                         cur.dispatch(tmpcmd);
987
988                 if (cur.result().dispatched())
989                         cur.clearSelection();
990
991                 break;
992         }
993
994         default:
995                 return false;
996         }
997
998         return true;
999 }
1000
1001
1002 docstring const BufferView::requestSelection()
1003 {
1004         if (!buffer_)
1005                 return docstring();
1006
1007         LCursor & cur = cursor_;
1008
1009         if (!cur.selection()) {
1010                 xsel_cache_.set = false;
1011                 return docstring();
1012         }
1013
1014         if (!xsel_cache_.set ||
1015             cur.top() != xsel_cache_.cursor ||
1016             cur.anchor_.top() != xsel_cache_.anchor)
1017         {
1018                 xsel_cache_.cursor = cur.top();
1019                 xsel_cache_.anchor = cur.anchor_.top();
1020                 xsel_cache_.set = cur.selection();
1021                 return cur.selectionAsString(false);
1022         }
1023         return docstring();
1024 }
1025
1026
1027 void BufferView::clearSelection()
1028 {
1029         if (buffer_) {
1030                 cursor_.clearSelection();
1031                 xsel_cache_.set = false;
1032         }
1033 }
1034
1035
1036 void BufferView::workAreaResize(int width, int height)
1037 {
1038         bool const widthChange = width != width_;
1039         bool const heightChange = height != height_;
1040
1041         // Update from work area
1042         width_ = width;
1043         height_ = height;
1044
1045         if (buffer_ && widthChange) {
1046                 // The WorkArea content needs a resize
1047                 resize();
1048         }
1049
1050         if (widthChange || heightChange)
1051                 update();
1052 }
1053
1054
1055 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1056 {
1057         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1058
1059         // This is only called for mouse related events including
1060         // LFUN_FILE_OPEN generated by drag-and-drop.
1061         FuncRequest cmd = cmd0;
1062
1063         if (!buffer_)
1064                 return false;
1065
1066         LCursor cur(*this);
1067         cur.push(buffer_->inset());
1068         cur.selection() = cursor_.selection();
1069
1070         // Doesn't go through lyxfunc, so we need to update
1071         // the layout choice etc. ourselves
1072
1073         // E.g. Qt mouse press when no buffer
1074         if (!buffer_)
1075                 return false;
1076
1077         // Either the inset under the cursor or the
1078         // surrounding LyXText will handle this event.
1079
1080         // Build temporary cursor.
1081         cmd.y = min(max(cmd.y, -1), height_);
1082         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1083         //lyxerr << BOOST_CURRENT_FUNCTION
1084         //       << " * hit inset at tip: " << inset << endl;
1085         //lyxerr << BOOST_CURRENT_FUNCTION
1086         //       << " * created temp cursor:" << cur << endl;
1087
1088         // Put anchor at the same position.
1089         cur.resetAnchor();
1090
1091         // Try to dispatch to an non-editable inset near this position
1092         // via the temp cursor. If the inset wishes to change the real
1093         // cursor it has to do so explicitly by using
1094         //  cur.bv().cursor() = cur;  (or similar)
1095         if (inset)
1096                 inset->dispatch(cur, cmd);
1097
1098         // Now dispatch to the temporary cursor. If the real cursor should
1099         // be modified, the inset's dispatch has to do so explicitly.
1100         if (!cur.result().dispatched())
1101                 cur.dispatch(cmd);
1102
1103         if (cur.result().dispatched()) {
1104                 // Redraw if requested or necessary.
1105                 if (cur.result().update())
1106                         update(Update::FitCursor | Update::Force);
1107                 else
1108                         update(Update::FitCursor | Update::MultiParSel);
1109         }
1110
1111         return true;
1112 }
1113
1114
1115 void BufferView::scroll(int lines)
1116 {
1117 //      if (!buffer_)
1118 //              return;
1119 //
1120 //      LyXText const * t = &buffer_->text();
1121 //      int const line_height = defaultRowHeight();
1122 //
1123 //      // The new absolute coordinate
1124 //      int new_top_y = top_y() + lines * line_height;
1125 //
1126 //      // Restrict to a valid value
1127 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1128 //      new_top_y = std::max(0, new_top_y);
1129 //
1130 //      scrollDocView(new_top_y);
1131 //
1132 //      // Update the scrollbar.
1133 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1134 }
1135
1136
1137 void BufferView::setCursorFromRow(int row)
1138 {
1139         int tmpid = -1;
1140         int tmppos = -1;
1141
1142         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1143
1144         if (tmpid == -1)
1145                 buffer_->text().setCursor(cursor_, 0, 0);
1146         else
1147                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1148 }
1149
1150
1151 void BufferView::gotoLabel(string const & label)
1152 {
1153         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1154                 vector<string> labels;
1155                 it->getLabelList(*buffer_, labels);
1156                 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1157                         setCursor(it);
1158                         update();
1159                         return;
1160                 }
1161         }
1162 }
1163
1164
1165 LyXText * BufferView::getLyXText()
1166 {
1167         LyXText * text = cursor_.innerText();
1168         BOOST_ASSERT(text);
1169         return text;
1170 }
1171
1172
1173 LyXText const * BufferView::getLyXText() const
1174 {
1175         LyXText const * text = cursor_.innerText();
1176         BOOST_ASSERT(text);
1177         return text;
1178 }
1179
1180
1181 int BufferView::workHeight() const
1182 {
1183         return height_;
1184 }
1185
1186
1187 void BufferView::setCursor(DocIterator const & dit)
1188 {
1189         size_t const n = dit.depth();
1190         for (size_t i = 0; i < n; ++i)
1191                 dit[i].inset().edit(cursor_, true);
1192
1193         cursor_.setCursor(dit);
1194         cursor_.selection() = false;
1195 }
1196
1197
1198 void BufferView::mouseSetCursor(LCursor & cur)
1199 {
1200         BOOST_ASSERT(&cur.bv() == this);
1201
1202         // Has the cursor just left the inset?
1203         bool badcursor = false;
1204         if (&cursor_.inset() != &cur.inset())
1205                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1206
1207         // do the dEPM magic if needed
1208         // FIXME: move this to InsetText::notifyCursorLeaves?
1209         if (!badcursor && cursor_.inTexted())
1210                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1211
1212         cursor_ = cur;
1213         cursor_.clearSelection();
1214         cursor_.setTargetX();
1215         finishUndo();
1216
1217 }
1218
1219
1220 void BufferView::putSelectionAt(DocIterator const & cur,
1221                                 int length, bool backwards)
1222 {
1223         cursor_.clearSelection();
1224
1225         setCursor(cur);
1226
1227         if (length) {
1228                 if (backwards) {
1229                         cursor_.pos() += length;
1230                         cursor_.setSelection(cursor_, -length);
1231                 } else
1232                         cursor_.setSelection(cursor_, length);
1233         }
1234 }
1235
1236
1237 LCursor & BufferView::cursor()
1238 {
1239         return cursor_;
1240 }
1241
1242
1243 LCursor const & BufferView::cursor() const
1244 {
1245         return cursor_;
1246 }
1247
1248
1249 lyx::pit_type BufferView::anchor_ref() const
1250 {
1251         return anchor_ref_;
1252 }
1253
1254
1255 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1256 {
1257         return metrics_info_;
1258 }
1259
1260
1261 void BufferView::updateMetrics(bool singlepar)
1262 {
1263         // Remove old position cache
1264         theCoords.clear();
1265         LyXText & buftext = buffer_->text();
1266         lyx::pit_type size = int(buftext.paragraphs().size());
1267
1268         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1269                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1270                 offset_ref_ = 0;
1271         }
1272
1273         lyx::pit_type const pit = anchor_ref_;
1274         int pit1 = pit;
1275         int pit2 = pit;
1276         size_t const npit = buftext.paragraphs().size();
1277
1278         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1279         // the (main text, not inset!) paragraph containing the cursor.
1280         // (if this paragraph contains insets etc., rebreaking will
1281         // recursively descend)
1282         if (!singlepar || pit == cursor_.bottom().pit())
1283                 buftext.redoParagraph(pit);
1284         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1285
1286         // Redo paragraphs above anchor if necessary; again, in Single Par
1287         // mode, only if we encounter the (main text) one having the cursor.
1288         int y1 = y0;
1289         while (y1 > 0 && pit1 > 0) {
1290                 y1 -= buftext.getPar(pit1).ascent();
1291                 --pit1;
1292                 if (!singlepar || pit1 == cursor_.bottom().pit())
1293                         buftext.redoParagraph(pit1);
1294                 y1 -= buftext.getPar(pit1).descent();
1295         }
1296
1297
1298         // Take care of ascent of first line
1299         y1 -= buftext.getPar(pit1).ascent();
1300
1301         // Normalize anchor for next time
1302         anchor_ref_ = pit1;
1303         offset_ref_ = -y1;
1304
1305         // Grey at the beginning is ugly
1306         if (pit1 == 0 && y1 > 0) {
1307                 y0 -= y1;
1308                 y1 = 0;
1309                 anchor_ref_ = 0;
1310         }
1311
1312         // Redo paragraphs below the anchor if necessary. Single par mode:
1313         // only the one containing the cursor if encountered.
1314         int y2 = y0;
1315         while (y2 < height_ && pit2 < int(npit) - 1) {
1316                 y2 += buftext.getPar(pit2).descent();
1317                 ++pit2;
1318                 if (!singlepar || pit2 == cursor_.bottom().pit())
1319                         buftext.redoParagraph(pit2);
1320                 y2 += buftext.getPar(pit2).ascent();
1321         }
1322
1323         // Take care of descent of last line
1324         y2 += buftext.getPar(pit2).descent();
1325
1326         // The coordinates of all these paragraphs are correct, cache them
1327         int y = y1;
1328         CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1329         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1330                 Paragraph const & par = buftext.getPar(pit);
1331                 y += par.ascent();
1332                 parPos[pit] = Point(0, y);
1333                 if (singlepar && pit == cursor_.bottom().pit()) {
1334                         // In Single Paragraph mode, collect here the
1335                         // y1 and y2 of the (one) paragraph the cursor is in
1336                         y1 = y - par.ascent();
1337                         y2 = y + par.descent();
1338                 }
1339                 y += par.descent();
1340         }
1341
1342         if (singlepar) {
1343                 // collect cursor paragraph iter bounds
1344                 pit1 = cursor_.bottom().pit();
1345                 pit2 = cursor_.bottom().pit();
1346         }
1347
1348         lyxerr[Debug::DEBUG]
1349                 << BOOST_CURRENT_FUNCTION
1350                 << " y1: " << y1
1351                 << " y2: " << y2
1352                 << " pit1: " << pit1
1353                 << " pit2: " << pit2
1354                 << " npit: " << npit
1355                 << " singlepar: " << singlepar
1356                 << "size: " << size
1357                 << endl;
1358
1359         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1360 }
1361
1362
1363 void BufferView::menuInsertLyXFile(string const & filenm)
1364 {
1365         BOOST_ASSERT(cursor_.inTexted());
1366         string filename = filenm;
1367
1368         if (filename.empty()) {
1369                 // Launch a file browser
1370                 string initpath = lyxrc.document_path;
1371
1372                 if (buffer_) {
1373                         string const trypath = buffer_->filePath();
1374                         // If directory is writeable, use this as default.
1375                         if (isDirWriteable(trypath))
1376                                 initpath = trypath;
1377                 }
1378
1379                 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1380                         LFUN_FILE_INSERT,
1381                         make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1382                                   string(lyxrc.document_path)),
1383                         make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1384                                   string(addPath(package().system_support(), "examples"))));
1385
1386                 FileDialog::Result result =
1387                         fileDlg.open(initpath,
1388                                      FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1389                                      string());
1390
1391                 if (result.first == FileDialog::Later)
1392                         return;
1393
1394                 filename = result.second;
1395
1396                 // check selected filename
1397                 if (filename.empty()) {
1398                         // emit message signal.
1399                         message(_("Canceled."));
1400                         return;
1401                 }
1402         }
1403
1404         // Get absolute path of file and add ".lyx"
1405         // to the filename if necessary
1406         filename = fileSearch(string(), filename, "lyx");
1407
1408         docstring const disp_fn = makeDisplayPath(filename);
1409         // emit message signal.
1410         message(bformat(_("Inserting document %1$s..."), disp_fn));
1411
1412         docstring res;
1413         Buffer buf("", false);
1414         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1415                 ErrorList & el = buffer_->errorList("Parse");
1416                 // Copy the inserted document error list into the current buffer one.
1417                 el = buf.errorList("Parse");
1418                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1419                                              buf.params().textclass, el);
1420                 res = _("Document %1$s inserted.");
1421         } else
1422                 res = _("Could not insert document %1$s");
1423
1424         // emit message signal.
1425         message(bformat(res, disp_fn));
1426         buffer_->errors("Parse");
1427         resize();
1428 }
1429
1430
1431 void BufferView::trackChanges()
1432 {
1433         bool const tracking = buffer_->params().tracking_changes;
1434
1435         if (!tracking) {
1436                 for_each(buffer_->par_iterator_begin(),
1437                          buffer_->par_iterator_end(),
1438                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1439                 buffer_->params().tracking_changes = true;
1440
1441                 // We cannot allow undos beyond the freeze point
1442                 buffer_->undostack().clear();
1443         } else {
1444                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1445                 if (lyx::find::findNextChange(this)) {
1446                         showDialog("changes");
1447                         return;
1448                 }
1449
1450                 for_each(buffer_->par_iterator_begin(),
1451                          buffer_->par_iterator_end(),
1452                          mem_fun_ref(&Paragraph::untrackChanges));
1453
1454                 buffer_->params().tracking_changes = false;
1455         }
1456
1457         buffer_->redostack().clear();
1458 }