]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Trivial whitespace fix.
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
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 "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "Text.h"
44 #include "TextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.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 namespace lyx {
83
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::make_pair;
98 using std::min;
99 using std::max;
100 using std::mem_fun_ref;
101 using std::string;
102 using std::vector;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 void BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the actual cursor position and anchor inside the
153                 // buffer so that it can be restored in case we rechange
154                 // to this buffer later on.
155                 buffer_->saveCursor(cursor_.selectionBegin(),
156                                     cursor_.selectionEnd());
157                 // update bookmark pit of the current buffer before switch
158                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160                         if (buffer()->fileName() != bm.filename.absFilename())
161                                 continue;
162                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
164                         pit_type new_pit;
165                         pos_type new_pos;
166                         int new_id;
167                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 // Ideally, the whole cursor stack should be saved, but session
173                 // currently can only handle bottom (whole document) level pit and pos.
174                 // That is to say, if a cursor is in a nested inset, it will be
175                 // restore to the left of the top level inset.
176                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
178         }
179
180         // If we're quitting lyx, don't bother updating stuff
181         if (quitting) {
182                 buffer_ = 0;
183                 return;
184         }
185
186         //FIXME Fix for bug 3440 is here.
187         // If we are closing current buffer, switch to the first in
188         // buffer list.
189         if (!b) {
190                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191                                     << " No Buffer!" << endl;
192                 // We are closing the buffer, use the first buffer as current
193                 //FIXME 3440
194                 // if (last_buffer_) buffer_ = last_buffer_;
195                 // also check that this is in theBufferList()?
196                 buffer_ = theBufferList().first();
197         } else {
198                 //FIXME 3440
199                 // last_buffer = buffer_;
200                 // Set current buffer
201                 buffer_ = b;
202         }
203
204         // Reset old cursor
205         cursor_ = Cursor(*this);
206         anchor_ref_ = 0;
207         offset_ref_ = 0;
208
209         if (!buffer_)
210                 return;
211
212         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213                                         << "Buffer addr: " << buffer_ << endl;
214         cursor_.push(buffer_->inset());
215         cursor_.resetAnchor();
216         buffer_->text().setCurrentFont(cursor_);
217         if (buffer_->getCursor().size() > 0 &&
218                         buffer_->getAnchor().size() > 0)
219         {
220                 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221                 cursor_.resetAnchor();
222                 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223                 cursor_.setSelection();
224                 // do not set selection to the new buffer because we
225                 // only paste recent selection.
226
227                 // Make sure that the restored cursor is not broken. This can happen for
228                 // example if this Buffer has been modified by another view.
229                 cursor_.fixIfBroken();
230         }
231         updateMetrics(false);
232         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233                 graphics::Previews::get().generateBufferPreviews(*buffer_);
234 }
235
236 // FIXME There is now no need for this to be in BufferView. It should all
237 // be moved to buffer_func.cpp. (Abdel)
238 Buffer * BufferView::loadLyXFile(FileName const & filename, bool auto_open)
239 {
240         // File already open?
241         if (theBufferList().exists(filename.absFilename())) {
242                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
243                 docstring text = bformat(_("The document %1$s is already "
244                                                      "loaded.\n\nDo you want to revert "
245                                                      "to the saved version?"), file);
246                 int const ret = Alert::prompt(_("Revert to saved document?"),
247                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
248
249                 if (ret != 0) {
250       Buffer * buf = theBufferList().getBuffer(filename.absFilename());
251                         setBuffer(buf);
252                         return buf;
253                 }
254                 // FIXME: should be LFUN_REVERT
255                 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
256                         return 0;
257                 // Fall through to new load. (Asger)
258                 buffer_ = 0;
259         }
260
261         Buffer * b = 0;
262
263         if (isFileReadable(filename)) {
264                 b = theBufferList().newBuffer(filename.absFilename());
265                 if (!lyx::loadLyXFile(b, filename)) {
266                         theBufferList().release(b);
267                         return 0;
268                 }
269         } else {
270                 docstring text = bformat(_("The document %1$s does not yet "
271                                                      "exist.\n\nDo you want to create "
272                                                      "a new document?"), from_utf8(filename.absFilename()));
273                 int const ret = Alert::prompt(_("Create new document?"),
274                          text, 0, 1, _("&Create"), _("Cancel"));
275
276                 if (ret == 0) {
277                         b = newFile(filename.absFilename(), string(), true);
278                         if (!b)
279                                 return 0;
280                 } else
281                         return 0;
282         }
283
284   if (!auto_open)
285         setBuffer(b);
286
287         return b;
288 }
289
290
291 void BufferView::resize()
292 {
293         if (!buffer_)
294                 return;
295
296         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
297
298         updateMetrics(false);
299 }
300
301
302 bool BufferView::fitCursor()
303 {
304         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
305                 frontend::FontMetrics const & fm =
306                         theFontMetrics(cursor_.getFont());
307                 int const asc = fm.maxAscent();
308                 int const des = fm.maxDescent();
309                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
310                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
311                         return false;
312         }
313         center();
314         return true;
315 }
316
317
318 bool BufferView::multiParSel()
319 {
320         if (!cursor_.selection())
321                 return false;
322         bool ret = multiparsel_cache_;
323         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
324         // Either this, or previous selection spans paragraphs
325         return ret || multiparsel_cache_;
326 }
327
328
329 bool BufferView::update(Update::flags flags)
330 {
331         // last_inset_ points to the last visited inset. This pointer may become
332         // invalid because of keyboard editing. Since all such operations
333         // causes screen update(), I reset last_inset_ to avoid such a problem.
334         last_inset_ = 0;
335         // This is close to a hot-path.
336         LYXERR(Debug::DEBUG)
337                 << BOOST_CURRENT_FUNCTION
338                 << "[fitcursor = " << (flags & Update::FitCursor)
339                 << ", forceupdate = " << (flags & Update::Force)
340                 << ", singlepar = " << (flags & Update::SinglePar)
341                 << "]  buffer: " << buffer_ << endl;
342
343         // Check needed to survive LyX startup
344         if (!buffer_)
345                 return false;
346
347         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
348
349         // Update macro store
350         if (!(cursor().inMathed() && cursor().inMacroMode()))
351                 buffer_->buildMacros();
352
353         // Now do the first drawing step if needed. This consists on updating
354         // the CoordCache in updateMetrics().
355         // The second drawing step is done in WorkArea::redraw() if needed.
356
357         // Case when no explicit update is requested.
358         if (!flags) {
359                 // no need to redraw anything.
360                 metrics_info_.update_strategy = NoScreenUpdate;
361                 return false;
362         }
363
364         if (flags == Update::Decoration) {
365                 metrics_info_.update_strategy = DecorationUpdate;
366                 return true;
367         }
368
369         if (flags == Update::FitCursor
370                 || flags == (Update::Decoration | Update::FitCursor)) {
371                 bool const fit_cursor = fitCursor();
372                 // tell the frontend to update the screen if needed.
373                 if (fit_cursor) {
374                         updateMetrics(false);
375                         return true;
376                 }
377                 if (flags & Update::Decoration) {
378                         metrics_info_.update_strategy = DecorationUpdate;
379                         return true;
380                 }
381                 // no screen update is needed.
382                 metrics_info_.update_strategy = NoScreenUpdate;
383                 return false;
384         }
385
386         bool full_metrics = flags & Update::Force;
387         if (flags & Update::MultiParSel)
388                 full_metrics |= multiParSel();
389
390         bool const single_par = !full_metrics;
391         updateMetrics(single_par);
392
393         if (flags & Update::FitCursor && fitCursor())
394                 updateMetrics(false);
395
396         // tell the frontend to update the screen.
397         return true;
398 }
399
400
401 void BufferView::updateScrollbar()
402 {
403         if (!buffer_) {
404                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
405                                      << " no text in updateScrollbar" << endl;
406                 scrollbarParameters_.reset();
407                 return;
408         }
409
410         Text & t = buffer_->text();
411         TextMetrics & tm = text_metrics_[&t];
412
413         int const parsize = int(t.paragraphs().size() - 1);
414         if (anchor_ref_ >  parsize)  {
415                 anchor_ref_ = parsize;
416                 offset_ref_ = 0;
417         }
418
419         LYXERR(Debug::GUI)
420                 << BOOST_CURRENT_FUNCTION
421                 << " Updating scrollbar: height: " << t.paragraphs().size()
422                 << " curr par: " << cursor_.bottom().pit()
423                 << " default height " << defaultRowHeight() << endl;
424
425         // It would be better to fix the scrollbar to understand
426         // values in [0..1] and divide everything by wh
427
428         // estimated average paragraph height:
429         if (wh_ == 0)
430                 wh_ = height_ / 4;
431
432         int h = tm.parMetrics(anchor_ref_).height();
433
434         // Normalize anchor/offset (MV):
435         while (offset_ref_ > h && anchor_ref_ < parsize) {
436                 anchor_ref_++;
437                 offset_ref_ -= h;
438                 h = tm.parMetrics(anchor_ref_).height();
439         }
440         // Look at paragraph heights on-screen
441         int sumh = 0;
442         int nh = 0;
443         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
444                 if (sumh > height_)
445                         break;
446                 int const h2 = tm.parMetrics(pit).height();
447                 sumh += h2;
448                 nh++;
449         }
450
451         BOOST_ASSERT(nh);
452         int const hav = sumh / nh;
453         // More realistic average paragraph height
454         if (hav > wh_)
455                 wh_ = hav;
456
457         BOOST_ASSERT(h);
458         scrollbarParameters_.height = (parsize + 1) * wh_;
459         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
460         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
461 }
462
463
464 ScrollbarParameters const & BufferView::scrollbarParameters() const
465 {
466         return scrollbarParameters_;
467 }
468
469
470 void BufferView::scrollDocView(int value)
471 {
472         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
473                            << "[ value = " << value << "]" << endl;
474
475         if (!buffer_)
476                 return;
477
478         Text & t = buffer_->text();
479         TextMetrics & tm = text_metrics_[&t];
480
481         float const bar = value / float(wh_ * t.paragraphs().size());
482
483         anchor_ref_ = int(bar * t.paragraphs().size());
484         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
485                 anchor_ref_ = int(t.paragraphs().size()) - 1;
486
487         tm.redoParagraph(anchor_ref_);
488         int const h = tm.parMetrics(anchor_ref_).height();
489         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
490         updateMetrics(false);
491 }
492
493
494 void BufferView::setCursorFromScrollbar()
495 {
496         if (!buffer_)
497                 return;
498
499         Text & t = buffer_->text();
500
501         int const height = 2 * defaultRowHeight();
502         int const first = height;
503         int const last = height_ - height;
504         Cursor & cur = cursor_;
505
506         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
507
508         switch (st) {
509         case bv_funcs::CUR_ABOVE:
510                 // We reset the cursor because bv_funcs::status() does not
511                 // work when the cursor is within mathed.
512                 cur.reset(buffer_->inset());
513                 t.setCursorFromCoordinates(cur, 0, first);
514                 cur.clearSelection();
515                 break;
516         case bv_funcs::CUR_BELOW:
517                 // We reset the cursor because bv_funcs::status() does not
518                 // work when the cursor is within mathed.
519                 cur.reset(buffer_->inset());
520                 t.setCursorFromCoordinates(cur, 0, last);
521                 cur.clearSelection();
522                 break;
523         case bv_funcs::CUR_INSIDE:
524                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
525                 int const newy = min(last, max(y, first));
526                 if (y != newy) {
527                         cur.reset(buffer_->inset());
528                         t.setCursorFromCoordinates(cur, 0, newy);
529                 }
530         }
531 }
532
533
534 Change const BufferView::getCurrentChange() const
535 {
536         if (!cursor_.selection())
537                 return Change(Change::UNCHANGED);
538
539         DocIterator dit = cursor_.selectionBegin();
540         return dit.paragraph().lookupChange(dit.pos());
541 }
542
543
544 void BufferView::saveBookmark(unsigned int idx)
545 {
546         // tenatively save bookmark, id and pos will be used to
547         // acturately locate a bookmark in a 'live' lyx session.
548         // pit and pos will be updated with bottom level pit/pos
549         // when lyx exits.
550         LyX::ref().session().bookmarks().save(
551                 FileName(buffer_->fileName()),
552                 cursor_.bottom().pit(),
553                 cursor_.bottom().pos(),
554                 cursor_.paragraph().id(),
555                 cursor_.pos(),
556                 idx
557         );
558         if (idx)
559                 // emit message signal.
560                 message(_("Save bookmark"));
561 }
562
563
564 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
565         int top_id, pos_type top_pos)
566 {
567         cursor_.clearSelection();
568
569         // if a valid par_id is given, try it first
570         // This is the case for a 'live' bookmark when unique paragraph ID
571         // is used to track bookmarks.
572         if (top_id > 0) {
573                 ParIterator par = buffer_->getParFromID(top_id);
574                 if (par != buffer_->par_iterator_end()) {
575                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
576                         // Some slices of the iterator may not be
577                         // reachable (e.g. closed collapsable inset)
578                         // so the dociterator may need to be
579                         // shortened. Otherwise, setCursor may crash
580                         // lyx when the cursor can not be set to these
581                         // insets.
582                         size_t const n = dit.depth();
583                         for (size_t i = 0; i < n; ++i)
584                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
585                                         dit.resize(i);
586                                         break;
587                                 }
588                         setCursor(dit);
589                         // Note: return bottom (document) level pit.
590                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
591                 }
592         }
593         // if top_id == 0, or searching through top_id failed
594         // This is the case for a 'restored' bookmark when only bottom
595         // (document level) pit was saved. Because of this, bookmark
596         // restoration is inaccurate. If a bookmark was within an inset,
597         // it will be restored to the left of the outmost inset that contains
598         // the bookmark.
599         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
600                 DocIterator it = doc_iterator_begin(buffer_->inset());
601                 it.pit() = bottom_pit;
602                 it.pos() = min(bottom_pos, it.paragraph().size());
603                 setCursor(it);
604                 return boost::make_tuple(it.pit(), it.pos(),
605                                          it.paragraph().id());
606         }
607         // both methods fail
608         return boost::make_tuple(pit_type(0), pos_type(0), 0);
609 }
610
611
612 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
613 {
614         if (lyxrc.rtl_support) {
615                 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
616                         if (intl_->keymap == Intl::PRIMARY)
617                                 intl_->keyMapSec();
618                 } else {
619                         if (intl_->keymap == Intl::SECONDARY)
620                                 intl_->keyMapPrim();
621                 }
622         }
623         
624         intl_->getTransManager().translateAndInsert(c, t, cur);
625 }
626
627
628 int BufferView::workWidth() const
629 {
630         return width_;
631 }
632
633
634 void BufferView::center()
635 {
636         CursorSlice & bot = cursor_.bottom();
637         TextMetrics & tm = text_metrics_[bot.text()];
638         pit_type const pit = bot.pit();
639         tm.redoParagraph(pit);
640         ParagraphMetrics const & pm = tm.parMetrics(pit);
641         anchor_ref_ = pit;
642         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
643                 + pm.ascent() - height_ / 2;
644 }
645
646
647 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
648 {
649         FuncStatus flag;
650
651         Cursor & cur = cursor_;
652
653         switch (cmd.action) {
654
655         case LFUN_UNDO:
656                 flag.enabled(!buffer_->undostack().empty());
657                 break;
658         case LFUN_REDO:
659                 flag.enabled(!buffer_->redostack().empty());
660                 break;
661         case LFUN_FILE_INSERT:
662         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
663         case LFUN_FILE_INSERT_PLAINTEXT:
664         case LFUN_BOOKMARK_SAVE:
665                 // FIXME: Actually, these LFUNS should be moved to Text
666                 flag.enabled(cur.inTexted());
667                 break;
668         case LFUN_FONT_STATE:
669         case LFUN_LABEL_INSERT:
670         case LFUN_PARAGRAPH_GOTO:
671         // FIXME handle non-trivially
672         case LFUN_OUTLINE_UP:
673         case LFUN_OUTLINE_DOWN:
674         case LFUN_OUTLINE_IN:
675         case LFUN_OUTLINE_OUT:
676         case LFUN_NOTE_NEXT:
677         case LFUN_REFERENCE_NEXT:
678         case LFUN_WORD_FIND:
679         case LFUN_MARK_OFF:
680         case LFUN_MARK_ON:
681         case LFUN_MARK_TOGGLE:
682         case LFUN_SCREEN_RECENTER:
683         case LFUN_BIBTEX_DATABASE_ADD:
684         case LFUN_BIBTEX_DATABASE_DEL:
685         case LFUN_WORDS_COUNT:
686         case LFUN_NEXT_INSET_TOGGLE:
687                 flag.enabled(true);
688                 break;
689
690         case LFUN_WORD_REPLACE:
691                 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
692                 break;
693
694         case LFUN_LABEL_GOTO: {
695                 flag.enabled(!cmd.argument().empty()
696                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
697                 break;
698         }
699
700         case LFUN_CHANGES_TRACK:
701                 flag.enabled(true);
702                 flag.setOnOff(buffer_->params().trackChanges);
703                 break;
704
705         case LFUN_CHANGES_OUTPUT:
706                 flag.enabled(buffer_);
707                 flag.setOnOff(buffer_->params().outputChanges);
708                 break;
709
710         case LFUN_CHANGES_MERGE:
711         case LFUN_CHANGE_NEXT:
712         case LFUN_ALL_CHANGES_ACCEPT:
713         case LFUN_ALL_CHANGES_REJECT:
714                 // TODO: context-sensitive enabling of LFUNs
715                 // In principle, these command should only be enabled if there
716                 // is a change in the document. However, without proper
717                 // optimizations, this will inevitably result in poor performance.
718                 flag.enabled(buffer_);
719                 break;
720
721         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
722                 flag.setOnOff(buffer_->params().compressed);
723                 break;
724         }
725
726         default:
727                 flag.enabled(false);
728         }
729
730         return flag;
731 }
732
733
734 Update::flags BufferView::dispatch(FuncRequest const & cmd)
735 {
736         //lyxerr << BOOST_CURRENT_FUNCTION
737         //       << [ cmd = " << cmd << "]" << endl;
738
739         // Make sure that the cached BufferView is correct.
740         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
741                 << " action[" << cmd.action << ']'
742                 << " arg[" << to_utf8(cmd.argument()) << ']'
743                 << " x[" << cmd.x << ']'
744                 << " y[" << cmd.y << ']'
745                 << " button[" << cmd.button() << ']'
746                 << endl;
747
748         // FIXME: this should not be possible.
749         if (!buffer_)
750                 return Update::None;
751
752         Cursor & cur = cursor_;
753         // Default Update flags.
754         Update::flags updateFlags = Update::Force | Update::FitCursor;
755
756         switch (cmd.action) {
757
758         case LFUN_UNDO:
759                 cur.message(_("Undo"));
760                 cur.clearSelection();
761                 if (!textUndo(*this)) {
762                         cur.message(_("No further undo information"));
763                         updateFlags = Update::None;
764                 }
765                 break;
766
767         case LFUN_REDO:
768                 cur.message(_("Redo"));
769                 cur.clearSelection();
770                 if (!textRedo(*this)) {
771                         cur.message(_("No further redo information"));
772                         updateFlags = Update::None;
773                 }
774                 break;
775
776         case LFUN_FILE_INSERT:
777                 // FIXME UNICODE
778                 menuInsertLyXFile(to_utf8(cmd.argument()));
779                 break;
780
781         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
782                 // FIXME UNICODE
783                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
784                 break;
785
786         case LFUN_FILE_INSERT_PLAINTEXT:
787                 // FIXME UNICODE
788                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
789                 break;
790
791         case LFUN_FONT_STATE:
792                 cur.message(cur.currentState());
793                 break;
794
795         case LFUN_BOOKMARK_SAVE:
796                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
797                 break;
798
799         case LFUN_LABEL_GOTO: {
800                 docstring label = cmd.argument();
801                 if (label.empty()) {
802                         InsetRef * inset =
803                                 getInsetByCode<InsetRef>(cursor_,
804                                                          Inset::REF_CODE);
805                         if (inset) {
806                                 label = inset->getParam("reference");
807                                 // persistent=false: use temp_bookmark
808                                 saveBookmark(0);
809                         }
810                 }
811
812                 if (!label.empty())
813                         gotoLabel(label);
814                 break;
815         }
816
817         case LFUN_PARAGRAPH_GOTO: {
818                 int const id = convert<int>(to_utf8(cmd.argument()));
819                 int i = 0;
820                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
821                         ParIterator par = b->getParFromID(id);
822                         if (par == b->par_iterator_end()) {
823                                 LYXERR(Debug::INFO)
824                                         << "No matching paragraph found! ["
825                                         << id << "]." << endl;
826                         } else {
827                                 LYXERR(Debug::INFO)
828                                         << "Paragraph " << par->id()
829                                         << " found in buffer `"
830                                         << b->fileName() << "'." << endl;
831
832                                 if (b == buffer_) {
833                                         // Set the cursor
834                                         setCursor(makeDocIterator(par, 0));
835                                 } else {
836                                         // Switch to other buffer view and resend cmd
837                                         theLyXFunc().dispatch(FuncRequest(
838                                                 LFUN_BUFFER_SWITCH, b->fileName()));
839                                         theLyXFunc().dispatch(cmd);
840                                         updateFlags = Update::None;
841                                 }
842                                 break;
843                         }
844                         ++i;
845                 }
846                 break;
847         }
848
849         case LFUN_OUTLINE_UP:
850                 toc::outline(toc::Up, cursor_);
851                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
852                 updateLabels(*buffer_);
853                 break;
854         case LFUN_OUTLINE_DOWN:
855                 toc::outline(toc::Down, cursor_);
856                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
857                 updateLabels(*buffer_);
858                 break;
859         case LFUN_OUTLINE_IN:
860                 toc::outline(toc::In, cursor_);
861                 updateLabels(*buffer_);
862                 break;
863         case LFUN_OUTLINE_OUT:
864                 toc::outline(toc::Out, cursor_);
865                 updateLabels(*buffer_);
866                 break;
867
868         case LFUN_NOTE_NEXT:
869                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
870                 break;
871
872         case LFUN_REFERENCE_NEXT: {
873                 vector<Inset_code> tmp;
874                 tmp.push_back(Inset::LABEL_CODE);
875                 tmp.push_back(Inset::REF_CODE);
876                 bv_funcs::gotoInset(this, tmp, true);
877                 break;
878         }
879
880         case LFUN_CHANGES_TRACK:
881                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
882                 break;
883
884         case LFUN_CHANGES_OUTPUT:
885                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
886                 if (buffer_->params().outputChanges) {
887                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
888                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
889                                           LaTeXFeatures::isAvailable("xcolor");
890
891                         if (!dvipost && !xcolorsoul) {
892                                 Alert::warning(_("Changes not shown in LaTeX output"),
893                                                _("Changes will not be highlighted in LaTeX output, "
894                                                  "because neither dvipost nor xcolor/soul are installed.\n"
895                                                  "Please install these packages or redefine "
896                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
897                         } else if (!xcolorsoul) {
898                                 Alert::warning(_("Changes not shown in LaTeX output"),
899                                                _("Changes will not be highlighted in LaTeX output "
900                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
901                                                  "Please install both packages or redefine "
902                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
903                         }
904                 }
905                 break;
906
907         case LFUN_CHANGE_NEXT:
908                 findNextChange(this);
909                 break;
910
911         case LFUN_CHANGES_MERGE:
912                 if (findNextChange(this))
913                         showDialog("changes");
914                 break;
915
916         case LFUN_ALL_CHANGES_ACCEPT:
917                 // select complete document
918                 cursor_.reset(buffer_->inset());
919                 cursor_.selHandle(true);
920                 buffer_->text().cursorBottom(cursor_);
921                 // accept everything in a single step to support atomic undo
922                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
923                 break;
924
925         case LFUN_ALL_CHANGES_REJECT:
926                 // select complete document
927                 cursor_.reset(buffer_->inset());
928                 cursor_.selHandle(true);
929                 buffer_->text().cursorBottom(cursor_);
930                 // reject everything in a single step to support atomic undo
931                 // Note: reject does not work recursively; the user may have to repeat the operation
932                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
933                 break;
934
935         case LFUN_WORD_FIND:
936                 find(this, cmd);
937                 break;
938
939         case LFUN_WORD_REPLACE:
940                 replace(this, cmd);
941                 break;
942
943         case LFUN_MARK_OFF:
944                 cur.clearSelection();
945                 cur.resetAnchor();
946                 cur.message(from_utf8(N_("Mark off")));
947                 break;
948
949         case LFUN_MARK_ON:
950                 cur.clearSelection();
951                 cur.mark() = true;
952                 cur.resetAnchor();
953                 cur.message(from_utf8(N_("Mark on")));
954                 break;
955
956         case LFUN_MARK_TOGGLE:
957                 cur.clearSelection();
958                 if (cur.mark()) {
959                         cur.mark() = false;
960                         cur.message(from_utf8(N_("Mark removed")));
961                 } else {
962                         cur.mark() = true;
963                         cur.message(from_utf8(N_("Mark set")));
964                 }
965                 cur.resetAnchor();
966                 break;
967
968         case LFUN_SCREEN_RECENTER:
969                 center();
970                 break;
971
972         case LFUN_BIBTEX_DATABASE_ADD: {
973                 Cursor tmpcur = cursor_;
974                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
975                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
976                                                 Inset::BIBTEX_CODE);
977                 if (inset) {
978                         if (inset->addDatabase(to_utf8(cmd.argument())))
979                                 buffer_->updateBibfilesCache();
980                 }
981                 break;
982         }
983
984         case LFUN_BIBTEX_DATABASE_DEL: {
985                 Cursor tmpcur = cursor_;
986                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
987                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
988                                                 Inset::BIBTEX_CODE);
989                 if (inset) {
990                         if (inset->delDatabase(to_utf8(cmd.argument())))
991                                 buffer_->updateBibfilesCache();
992                 }
993                 break;
994         }
995
996         case LFUN_WORDS_COUNT: {
997                 DocIterator from, to;
998                 if (cur.selection()) {
999                         from = cur.selectionBegin();
1000                         to = cur.selectionEnd();
1001                 } else {
1002                         from = doc_iterator_begin(buffer_->inset());
1003                         to = doc_iterator_end(buffer_->inset());
1004                 }
1005                 int const count = countWords(from, to);
1006                 docstring message;
1007                 if (count != 1) {
1008                         if (cur.selection())
1009                                 message = bformat(_("%1$d words in selection."),
1010                                           count);
1011                                 else
1012                                         message = bformat(_("%1$d words in document."),
1013                                                           count);
1014                 }
1015                 else {
1016                         if (cur.selection())
1017                                 message = _("One word in selection.");
1018                         else
1019                                 message = _("One word in document.");
1020                 }
1021
1022                 Alert::information(_("Count words"), message);
1023         }
1024                 break;
1025
1026         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1027                 // turn compression on/off
1028                 buffer_->params().compressed = !buffer_->params().compressed;
1029                 break;
1030
1031         case LFUN_NEXT_INSET_TOGGLE: {
1032                 // this is the real function we want to invoke
1033                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1034                 // if there is an inset at cursor, see whether it
1035                 // wants to toggle.
1036                 Inset * inset = cur.nextInset();
1037                 if (inset && inset->isActive()) {
1038                         Cursor tmpcur = cur;
1039                         tmpcur.pushLeft(*inset);
1040                         inset->dispatch(tmpcur, tmpcmd);
1041                         if (tmpcur.result().dispatched()) {
1042                                 cur.dispatched();
1043                         }
1044                 }
1045                 // if it did not work, try the underlying inset.
1046                 if (!cur.result().dispatched())
1047                         cur.dispatch(tmpcmd);
1048
1049                 if (cur.result().dispatched())
1050                         cur.clearSelection();
1051
1052                 break;
1053         }
1054
1055         default:
1056                 updateFlags = Update::None;
1057         }
1058
1059         return updateFlags;
1060 }
1061
1062
1063 docstring const BufferView::requestSelection()
1064 {
1065         if (!buffer_)
1066                 return docstring();
1067
1068         Cursor & cur = cursor_;
1069
1070         if (!cur.selection()) {
1071                 xsel_cache_.set = false;
1072                 return docstring();
1073         }
1074
1075         if (!xsel_cache_.set ||
1076             cur.top() != xsel_cache_.cursor ||
1077             cur.anchor_.top() != xsel_cache_.anchor)
1078         {
1079                 xsel_cache_.cursor = cur.top();
1080                 xsel_cache_.anchor = cur.anchor_.top();
1081                 xsel_cache_.set = cur.selection();
1082                 return cur.selectionAsString(false);
1083         }
1084         return docstring();
1085 }
1086
1087
1088 void BufferView::clearSelection()
1089 {
1090         if (buffer_) {
1091                 cursor_.clearSelection();
1092                 // Clear the selection buffer. Otherwise a subsequent
1093                 // middle-mouse-button paste would use the selection buffer,
1094                 // not the more current external selection.
1095                 cap::clearSelection();
1096                 xsel_cache_.set = false;
1097                 // The buffer did not really change, but this causes the
1098                 // redraw we need because we cleared the selection above.
1099                 buffer_->changed();
1100         }
1101 }
1102
1103
1104 void BufferView::workAreaResize(int width, int height)
1105 {
1106         // Update from work area
1107         width_ = width;
1108         height_ = height;
1109
1110         // The complete text metrics will be redone.
1111         text_metrics_.clear();
1112
1113         if (buffer_)
1114                 resize();
1115 }
1116
1117
1118 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1119 {
1120         pit_type pit = text.getPitNearY(*this, y);
1121         BOOST_ASSERT(pit != -1);
1122         Paragraph const & par = text.getPar(pit);
1123
1124         LYXERR(Debug::DEBUG)
1125                 << BOOST_CURRENT_FUNCTION
1126                 << ": x: " << x
1127                 << " y: " << y
1128                 << "  pit: " << pit
1129                 << endl;
1130         InsetList::const_iterator iit = par.insetlist.begin();
1131         InsetList::const_iterator iend = par.insetlist.end();
1132         for (; iit != iend; ++iit) {
1133                 Inset * const inset = iit->inset;
1134                 if (inset->covers(*this, x, y)) {
1135                         if (!inset->descendable())
1136                                 // No need to go further down if the inset is not
1137                                 // descendable.
1138                                 return inset;
1139
1140                         size_t cell_number = inset->nargs();
1141                         // Check all the inner cell.
1142                         for (size_t i = 0; i != cell_number; ++i) {
1143                                 Text const * inner_text = inset->getText(i);
1144                                 if (inner_text) {
1145                                         // Try deeper.
1146                                         Inset const * inset_deeper =
1147                                                 getCoveringInset(*inner_text, x, y);
1148                                         if (inset_deeper)
1149                                                 return inset_deeper;
1150                                 }
1151                         }
1152
1153                         LYXERR(Debug::DEBUG)
1154                                 << BOOST_CURRENT_FUNCTION
1155                                 << ": Hit inset: " << inset << endl;
1156                         return inset;
1157                 }
1158         }
1159         LYXERR(Debug::DEBUG)
1160                 << BOOST_CURRENT_FUNCTION
1161                 << ": No inset hit. " << endl;
1162         return 0;
1163 }
1164
1165
1166 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1167 {
1168         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1169
1170         // This is only called for mouse related events including
1171         // LFUN_FILE_OPEN generated by drag-and-drop.
1172         FuncRequest cmd = cmd0;
1173
1174         // E.g. Qt mouse press when no buffer
1175         if (!buffer_)
1176                 return false;
1177
1178         Cursor cur(*this);
1179         cur.push(buffer_->inset());
1180         cur.selection() = cursor_.selection();
1181
1182         // Either the inset under the cursor or the
1183         // surrounding Text will handle this event.
1184
1185         // make sure we stay within the screen...
1186         cmd.y = min(max(cmd.y, -1), height_);
1187
1188         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1189
1190                 // Get inset under mouse, if there is one.
1191                 Inset const * covering_inset =
1192                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1193                 if (covering_inset == last_inset_)
1194                         // Same inset, no need to do anything...
1195                         return false;
1196
1197                 bool need_redraw = false;
1198                 // const_cast because of setMouseHover().
1199                 Inset * inset = const_cast<Inset *>(covering_inset);
1200                 if (last_inset_)
1201                         // Remove the hint on the last hovered inset (if any).
1202                         need_redraw |= last_inset_->setMouseHover(false);
1203                 if (inset)
1204                         // Highlighted the newly hovered inset (if any).
1205                         need_redraw |= inset->setMouseHover(true);
1206                 last_inset_ = inset;
1207
1208                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1209                 // not expose the button for redraw. We adjust here the metrics dimension
1210                 // to enable a full redraw.
1211                 // FIXME: It is possible to redraw only the area around the button!
1212                 if (need_redraw
1213                         && metrics_info_.update_strategy == SingleParUpdate) {
1214                         // FIXME: It should be possible to redraw only the area around
1215                         // the button by doing this:
1216                         //
1217                         //metrics_info_.singlepar = false;
1218                         //metrics_info_.y1 = ymin of button;
1219                         //metrics_info_.y2 = ymax of button;
1220                         //
1221                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1222                         // between background updates and text updates. So we use the hammer
1223                         // solution for now. We could also avoid the updateMetrics() below
1224                         // by using the first and last pit of the CoordCache. Have a look
1225                         // at Text::getPitNearY() to see what I mean.
1226                         //
1227                         //metrics_info_.pit1 = first pit of CoordCache;
1228                         //metrics_info_.pit2 = last pit of CoordCache;
1229                         //metrics_info_.singlepar = false;
1230                         //metrics_info_.y1 = 0;
1231                         //metrics_info_.y2 = height_;
1232                         //
1233                         updateMetrics(false);
1234                 }
1235
1236                 // This event (moving without mouse click) is not passed further.
1237                 // This should be changed if it is further utilized.
1238                 return need_redraw;
1239         }
1240
1241         // Build temporary cursor.
1242         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1243
1244         // Put anchor at the same position.
1245         cur.resetAnchor();
1246
1247         // Try to dispatch to an non-editable inset near this position
1248         // via the temp cursor. If the inset wishes to change the real
1249         // cursor it has to do so explicitly by using
1250         //  cur.bv().cursor() = cur;  (or similar)
1251         if (inset) {
1252                 inset->dispatch(cur, cmd);
1253         }
1254
1255         // Now dispatch to the temporary cursor. If the real cursor should
1256         // be modified, the inset's dispatch has to do so explicitly.
1257         if (!cur.result().dispatched())
1258                 cur.dispatch(cmd);
1259
1260         // Redraw if requested and necessary.
1261         if (cur.result().dispatched() && cur.result().update())
1262                 return update(cur.result().update());
1263
1264         return false;
1265 }
1266
1267
1268 void BufferView::scroll(int /*lines*/)
1269 {
1270 //      if (!buffer_)
1271 //              return;
1272 //
1273 //      Text const * t = &buffer_->text();
1274 //      int const line_height = defaultRowHeight();
1275 //
1276 //      // The new absolute coordinate
1277 //      int new_top_y = top_y() + lines * line_height;
1278 //
1279 //      // Restrict to a valid value
1280 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1281 //      new_top_y = std::max(0, new_top_y);
1282 //
1283 //      scrollDocView(new_top_y);
1284 //
1285 }
1286
1287
1288 void BufferView::setCursorFromRow(int row)
1289 {
1290         int tmpid = -1;
1291         int tmppos = -1;
1292
1293         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1294
1295         if (tmpid == -1)
1296                 buffer_->text().setCursor(cursor_, 0, 0);
1297         else
1298                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1299 }
1300
1301
1302 void BufferView::gotoLabel(docstring const & label)
1303 {
1304         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1305                 vector<docstring> labels;
1306                 it->getLabelList(*buffer_, labels);
1307                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1308                         setCursor(it);
1309                         update();
1310                         return;
1311                 }
1312         }
1313 }
1314
1315
1316 TextMetrics const & BufferView::textMetrics(Text const * t) const
1317 {
1318         return const_cast<BufferView *>(this)->textMetrics(t);
1319 }
1320
1321
1322 TextMetrics & BufferView::textMetrics(Text const * t)
1323 {
1324         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1325         if (tmc_it == text_metrics_.end()) {
1326                 tmc_it = text_metrics_.insert(
1327                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1328         }
1329         return tmc_it->second;
1330 }
1331
1332
1333 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1334                 pit_type pit) const
1335 {
1336         return textMetrics(t).parMetrics(pit);
1337 }
1338
1339
1340 int BufferView::workHeight() const
1341 {
1342         return height_;
1343 }
1344
1345
1346 void BufferView::setCursor(DocIterator const & dit)
1347 {
1348         size_t const n = dit.depth();
1349         for (size_t i = 0; i < n; ++i)
1350                 dit[i].inset().edit(cursor_, true);
1351
1352         cursor_.setCursor(dit);
1353         cursor_.selection() = false;
1354 }
1355
1356
1357 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1358 {
1359         // Would be wrong to delete anything if we have a selection.
1360         if (cur.selection())
1361                 return false;
1362
1363         bool need_anchor_change = false;
1364         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1365                 need_anchor_change);
1366
1367         if (need_anchor_change)
1368                 cur.resetAnchor();
1369
1370         if (!changed)
1371                 return false;
1372
1373         updateLabels(*buffer_);
1374
1375         updateMetrics(false);
1376         buffer_->changed();
1377         return true;
1378 }
1379
1380
1381 bool BufferView::mouseSetCursor(Cursor & cur)
1382 {
1383         BOOST_ASSERT(&cur.bv() == this);
1384
1385         // Has the cursor just left the inset?
1386         bool badcursor = false;
1387         bool leftinset = (&cursor_.inset() != &cur.inset());
1388         if (leftinset)
1389                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1390
1391         // do the dEPM magic if needed
1392         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1393         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1394         // the leftinset bool would not be necessary (badcursor instead).
1395         bool update = leftinset;
1396         if (!badcursor && cursor_.inTexted())
1397                 update |= checkDepm(cur, cursor_);
1398
1399         // if the cursor was in an empty script inset and the new
1400         // position is in the nucleus of the inset, notifyCursorLeaves
1401         // will kill the script inset itself. So we check all the
1402         // elements of the cursor to make sure that they are correct.
1403         // For an example, see bug 2933:
1404         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1405         // The code below could maybe be moved to a DocIterator method.
1406         //lyxerr << "cur before " << cur <<std::endl;
1407         DocIterator dit(cur.inset());
1408         dit.push_back(cur.bottom());
1409         size_t i = 1;
1410         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1411                 dit.push_back(cur[i]);
1412                 ++i;
1413         }
1414         //lyxerr << "5 cur after" << dit <<std::endl;
1415
1416         cursor_.setCursor(dit);
1417         cursor_.boundary(cur.boundary());
1418         cursor_.clearSelection();
1419         finishUndo();
1420         return update;
1421 }
1422
1423
1424 void BufferView::putSelectionAt(DocIterator const & cur,
1425                                 int length, bool backwards)
1426 {
1427         cursor_.clearSelection();
1428
1429         setCursor(cur);
1430
1431         if (length) {
1432                 if (backwards) {
1433                         cursor_.pos() += length;
1434                         cursor_.setSelection(cursor_, -length);
1435                 } else
1436                         cursor_.setSelection(cursor_, length);
1437                 cap::saveSelection(cursor_);
1438         }
1439 }
1440
1441
1442 Cursor & BufferView::cursor()
1443 {
1444         return cursor_;
1445 }
1446
1447
1448 Cursor const & BufferView::cursor() const
1449 {
1450         return cursor_;
1451 }
1452
1453
1454 pit_type BufferView::anchor_ref() const
1455 {
1456         return anchor_ref_;
1457 }
1458
1459
1460 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1461 {
1462         return metrics_info_;
1463 }
1464
1465
1466 // FIXME: We should split-up updateMetrics() for the singlepar case.
1467 void BufferView::updateMetrics(bool singlepar)
1468 {
1469         Text & buftext = buffer_->text();
1470         TextMetrics & tm = textMetrics(&buftext);
1471         pit_type size = int(buftext.paragraphs().size());
1472
1473         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1474                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1475                 offset_ref_ = 0;
1476         }
1477
1478         // If the paragraph metrics has changed, we can not
1479         // use the singlepar optimisation.
1480         if (singlepar
1481                 // In Single Paragraph mode, rebreak only
1482                 // the (main text, not inset!) paragraph containing the cursor.
1483                 // (if this paragraph contains insets etc., rebreaking will
1484                 // recursively descend)
1485                 && tm.redoParagraph(cursor_.bottom().pit()))
1486                 singlepar = false;
1487
1488         pit_type const pit = anchor_ref_;
1489         int pit1 = pit;
1490         int pit2 = pit;
1491         size_t const npit = buftext.paragraphs().size();
1492
1493         // Rebreak anchor paragraph.
1494         if (!singlepar)
1495                 tm.redoParagraph(pit);
1496
1497         // Clear out the position cache in case of full screen redraw.
1498         if (!singlepar)
1499                 coord_cache_.clear();
1500
1501         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1502
1503         // Redo paragraphs above anchor if necessary.
1504         int y1 = y0;
1505         while (y1 > 0 && pit1 > 0) {
1506                 y1 -= tm.parMetrics(pit1).ascent();
1507                 --pit1;
1508                 if (!singlepar)
1509                         tm.redoParagraph(pit1);
1510                 y1 -= tm.parMetrics(pit1).descent();
1511         }
1512
1513
1514         // Take care of ascent of first line
1515         y1 -= tm.parMetrics(pit1).ascent();
1516
1517         // Normalize anchor for next time
1518         anchor_ref_ = pit1;
1519         offset_ref_ = -y1;
1520
1521         // Grey at the beginning is ugly
1522         if (pit1 == 0 && y1 > 0) {
1523                 y0 -= y1;
1524                 y1 = 0;
1525                 anchor_ref_ = 0;
1526         }
1527
1528         // Redo paragraphs below the anchor if necessary.
1529         int y2 = y0;
1530         while (y2 < height_ && pit2 < int(npit) - 1) {
1531                 y2 += tm.parMetrics(pit2).descent();
1532                 ++pit2;
1533                 if (!singlepar)
1534                         tm.redoParagraph(pit2);
1535                 y2 += tm.parMetrics(pit2).ascent();
1536         }
1537
1538         // Take care of descent of last line
1539         y2 += tm.parMetrics(pit2).descent();
1540
1541         // The coordinates of all these paragraphs are correct, cache them
1542         int y = y1;
1543         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1544         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1545                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1546                 y += pm.ascent();
1547                 parPos[pit] = Point(0, y);
1548                 if (singlepar && pit == cursor_.bottom().pit()) {
1549                         // In Single Paragraph mode, collect here the
1550                         // y1 and y2 of the (one) paragraph the cursor is in
1551                         y1 = y - pm.ascent();
1552                         y2 = y + pm.descent();
1553                 }
1554                 y += pm.descent();
1555         }
1556
1557         if (singlepar) {
1558                 // collect cursor paragraph iter bounds
1559                 pit1 = cursor_.bottom().pit();
1560                 pit2 = cursor_.bottom().pit();
1561         }
1562
1563         LYXERR(Debug::DEBUG)
1564                 << BOOST_CURRENT_FUNCTION
1565                 << " y1: " << y1
1566                 << " y2: " << y2
1567                 << " pit1: " << pit1
1568                 << " pit2: " << pit2
1569                 << " npit: " << npit
1570                 << " singlepar: " << singlepar
1571                 << "size: " << size
1572                 << endl;
1573
1574         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1575                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1576
1577         if (lyxerr.debugging(Debug::WORKAREA)) {
1578                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1579                 coord_cache_.dump();
1580         }
1581 }
1582
1583
1584 void BufferView::menuInsertLyXFile(string const & filenm)
1585 {
1586         BOOST_ASSERT(cursor_.inTexted());
1587         string filename = filenm;
1588
1589         if (filename.empty()) {
1590                 // Launch a file browser
1591                 // FIXME UNICODE
1592                 string initpath = lyxrc.document_path;
1593
1594                 if (buffer_) {
1595                         string const trypath = buffer_->filePath();
1596                         // If directory is writeable, use this as default.
1597                         if (isDirWriteable(FileName(trypath)))
1598                                 initpath = trypath;
1599                 }
1600
1601                 // FIXME UNICODE
1602                 FileDialog fileDlg(_("Select LyX document to insert"),
1603                         LFUN_FILE_INSERT,
1604                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1605                         make_pair(_("Examples|#E#e"),
1606                                     from_utf8(addPath(package().system_support().absFilename(),
1607                                     "examples"))));
1608
1609                 FileDialog::Result result =
1610                         fileDlg.open(from_utf8(initpath),
1611                                      FileFilterList(_("LyX Documents (*.lyx)")),
1612                                      docstring());
1613
1614                 if (result.first == FileDialog::Later)
1615                         return;
1616
1617                 // FIXME UNICODE
1618                 filename = to_utf8(result.second);
1619
1620                 // check selected filename
1621                 if (filename.empty()) {
1622                         // emit message signal.
1623                         message(_("Canceled."));
1624                         return;
1625                 }
1626         }
1627
1628         // Get absolute path of file and add ".lyx"
1629         // to the filename if necessary
1630         filename = fileSearch(string(), filename, "lyx").absFilename();
1631
1632         docstring const disp_fn = makeDisplayPath(filename);
1633         // emit message signal.
1634         message(bformat(_("Inserting document %1$s..."), disp_fn));
1635
1636         docstring res;
1637         Buffer buf("", false);
1638         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1639                 ErrorList & el = buffer_->errorList("Parse");
1640                 // Copy the inserted document error list into the current buffer one.
1641                 el = buf.errorList("Parse");
1642                 recordUndo(cursor_);
1643                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1644                                              buf.params().textclass, el);
1645                 res = _("Document %1$s inserted.");
1646         } else
1647                 res = _("Could not insert document %1$s");
1648
1649         // emit message signal.
1650         message(bformat(res, disp_fn));
1651         buffer_->errors("Parse");
1652         resize();
1653 }
1654
1655 } // namespace lyx