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