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