]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
new \lyxline difinition, fixes also bug 1988:
[lyx.git] / src / buffer_funcs.C
1 /**
2  * \file buffer_funcs.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "buffer.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "dociterator.h"
20 #include "counters.h"
21 #include "errorlist.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "gettext.h"
25 #include "language.h"
26 #include "LaTeX.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
33 #include "lyxvc.h"
34 #include "texrow.h"
35 #include "TocBackend.h"
36 #include "vc-backend.h"
37
38 #include "frontends/Alert.h"
39
40 #include "insets/insetbibitem.h"
41 #include "insets/insetcaption.h"
42 #include "insets/insetinclude.h"
43
44 #include "support/filetools.h"
45 #include "support/fs_extras.h"
46 #include "support/lyxlib.h"
47
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
50
51
52 namespace lyx {
53
54 using namespace std;
55
56 using support::bformat;
57 using support::FileName;
58 using support::libFileSearch;
59 using support::makeAbsPath;
60 using support::makeDisplayPath;
61 using support::onlyFilename;
62 using support::onlyPath;
63 using support::unlink;
64
65 using std::min;
66 using std::string;
67
68 namespace Alert = frontend::Alert;
69 namespace fs = boost::filesystem;
70
71 namespace {
72
73 bool readFile(Buffer * const b, FileName const & s)
74 {
75         BOOST_ASSERT(b);
76
77         // File information about normal file
78         if (!fs::exists(s.toFilesystemEncoding())) {
79                 docstring const file = makeDisplayPath(s.absFilename(), 50);
80                 docstring text = bformat(_("The specified document\n%1$s"
81                                                      "\ncould not be read."), file);
82                 Alert::error(_("Could not read document"), text);
83                 return false;
84         }
85
86         // Check if emergency save file exists and is newer.
87         FileName const e(s.absFilename() + ".emergency");
88
89         if (fs::exists(e.toFilesystemEncoding()) &&
90             fs::exists(s.toFilesystemEncoding()) &&
91             fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
92         {
93                 docstring const file = makeDisplayPath(s.absFilename(), 20);
94                 docstring const text =
95                         bformat(_("An emergency save of the document "
96                                   "%1$s exists.\n\n"
97                                                "Recover emergency save?"), file);
98                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
99                                       _("&Recover"),  _("&Load Original"),
100                                       _("&Cancel")))
101                 {
102                 case 0:
103                         // the file is not saved if we load the emergency file.
104                         b->markDirty();
105                         return b->readFile(e);
106                 case 1:
107                         break;
108                 default:
109                         return false;
110                 }
111         }
112
113         // Now check if autosave file is newer.
114         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
115
116         if (fs::exists(a.toFilesystemEncoding()) &&
117             fs::exists(s.toFilesystemEncoding()) &&
118             fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
119         {
120                 docstring const file = makeDisplayPath(s.absFilename(), 20);
121                 docstring const text =
122                         bformat(_("The backup of the document "
123                                   "%1$s is newer.\n\nLoad the "
124                                                "backup instead?"), file);
125                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
126                                       _("&Load backup"), _("Load &original"),
127                                       _("&Cancel") ))
128                 {
129                 case 0:
130                         // the file is not saved if we load the autosave file.
131                         b->markDirty();
132                         return b->readFile(a);
133                 case 1:
134                         // Here we delete the autosave
135                         unlink(a);
136                         break;
137                 default:
138                         return false;
139                 }
140         }
141         return b->readFile(s);
142 }
143
144
145 } // namespace anon
146
147
148
149 bool loadLyXFile(Buffer * b, FileName const & s)
150 {
151         BOOST_ASSERT(b);
152
153         if (fs::is_readable(s.toFilesystemEncoding())) {
154                 if (readFile(b, s)) {
155                         b->lyxvc().file_found_hook(s);
156                         if (!fs::is_writable(s.toFilesystemEncoding()))
157                                 b->setReadonly(true);
158                         return true;
159                 }
160         } else {
161                 docstring const file = makeDisplayPath(s.absFilename(), 20);
162                 // Here we probably should run
163                 if (LyXVC::file_not_found_hook(s)) {
164                         docstring const text =
165                                 bformat(_("Do you want to retrieve the document"
166                                                        " %1$s from version control?"), file);
167                         int const ret = Alert::prompt(_("Retrieve from version control?"),
168                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
169
170                         if (ret == 0) {
171                                 // How can we know _how_ to do the checkout?
172                                 // With the current VC support it has to be,
173                                 // a RCS file since CVS do not have special ,v files.
174                                 RCS::retrieve(s);
175                                 return loadLyXFile(b, s);
176                         }
177                 }
178         }
179         return false;
180 }
181
182 // FIXME newFile() should probably be a member method of Application...
183 Buffer * newFile(string const & filename, string const & templatename,
184                  bool const isNamed)
185 {
186         // get a free buffer
187         Buffer * b = theBufferList().newBuffer(filename);
188         BOOST_ASSERT(b);
189
190         FileName tname;
191         // use defaults.lyx as a default template if it exists.
192         if (templatename.empty())
193                 tname = libFileSearch("templates", "defaults.lyx");
194         else
195                 tname = makeAbsPath(templatename);
196
197         if (!tname.empty()) {
198                 if (!b->readFile(tname)) {
199                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
200                         docstring const text  = bformat(
201                                 _("The specified document template\n%1$s\ncould not be read."),
202                                 file);
203                         Alert::error(_("Could not read template"), text);
204                         theBufferList().release(b);
205                         return 0;
206                 }
207         }
208
209         if (!isNamed) {
210                 b->setUnnamed();
211                 b->setFileName(filename);
212         }
213
214         b->setReadonly(false);
215         b->fully_loaded(true);
216         b->updateDocLang(b->params().language);
217
218         return b;
219 }
220
221
222 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
223                                   ErrorList & errorList)
224 {
225         TeXErrors::Errors::const_iterator cit = terr.begin();
226         TeXErrors::Errors::const_iterator end = terr.end();
227
228         for (; cit != end; ++cit) {
229                 int id_start = -1;
230                 int pos_start = -1;
231                 int errorrow = cit->error_in_line;
232                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
233                                                        pos_start);
234                 int id_end = -1;
235                 int pos_end = -1;
236                 do {
237                         ++errorrow;
238                         found = buf.texrow().getIdFromRow(errorrow, id_end,
239                                                           pos_end);
240                 } while (found && id_start == id_end && pos_start == pos_end);
241
242                 errorList.push_back(ErrorItem(cit->error_desc,
243                         cit->error_text, id_start, pos_start, pos_end));
244         }
245 }
246
247
248 string const bufferFormat(Buffer const & buffer)
249 {
250         if (buffer.isDocBook())
251                 return "docbook";
252         else if (buffer.isLiterate())
253                 return "literate";
254         else
255                 return "latex";
256 }
257
258
259 int countWords(DocIterator const & from, DocIterator const & to)
260 {
261         int count = 0;
262         bool inword = false;
263         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
264                 // Copied and adapted from isLetter() in ControlSpellChecker
265                 if (dit.inTexted()
266                     && dit.pos() != dit.lastpos()
267                     && dit.paragraph().isLetter(dit.pos())
268                     && !dit.paragraph().isDeleted(dit.pos())) {
269                         if (!inword) {
270                                 ++count;
271                                 inword = true;
272                         }
273                 } else if (inword)
274                         inword = false;
275         }
276
277         return count;
278 }
279
280
281 namespace {
282
283 depth_type getDepth(DocIterator const & it)
284 {
285         depth_type depth = 0;
286         for (size_t i = 0 ; i < it.depth() ; ++i)
287                 if (!it[i].inset().inMathed())
288                         depth += it[i].paragraph().getDepth() + 1;
289         // remove 1 since the outer inset does not count
290         return depth - 1;
291 }
292
293 depth_type getItemDepth(ParIterator const & it)
294 {
295         Paragraph const & par = *it;
296         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
297
298         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
299                 return 0;
300
301         // this will hold the lowest depth encountered up to now.
302         depth_type min_depth = getDepth(it);
303         ParIterator prev_it = it;
304         while (true) {
305                 if (prev_it.pit())
306                         --prev_it.top().pit();
307                 else {
308                         // start of nested inset: go to outer par
309                         prev_it.pop_back();
310                         if (prev_it.empty()) {
311                                 // start of document: nothing to do
312                                 return 0;
313                         }
314                 }
315
316                 // We search for the first paragraph with same label
317                 // that is not more deeply nested.
318                 Paragraph & prev_par = *prev_it;
319                 depth_type const prev_depth = getDepth(prev_it);
320                 if (labeltype == prev_par.layout()->labeltype) {
321                         if (prev_depth < min_depth) {
322                                 return prev_par.itemdepth + 1;
323                         }
324                         else if (prev_depth == min_depth) {
325                                 return prev_par.itemdepth;
326                         }
327                 }
328                 min_depth = std::min(min_depth, prev_depth);
329                 // small optimization: if we are at depth 0, we won't
330                 // find anything else
331                 if (prev_depth == 0) {
332                         return 0;
333                 }
334         }
335 }
336
337
338 bool needEnumCounterReset(ParIterator const & it)
339 {
340         Paragraph const & par = *it;
341         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
342         depth_type const cur_depth = par.getDepth();
343         ParIterator prev_it = it;
344         while (prev_it.pit()) {
345                 --prev_it.top().pit();
346                 Paragraph const & prev_par = *prev_it;
347                 if (prev_par.getDepth() <= cur_depth)
348                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
349         }
350         // start of nested inset: reset
351         return true;
352 }
353
354
355 void setCaptionLabels(InsetBase & inset, Floating const & fl,
356                 Counters & counters)
357 {
358         LyXText * text = inset.getText(0);
359         if (!text)
360                 return;
361
362         ParagraphList & pars = text->paragraphs();
363         if (pars.empty())
364                 return;
365
366         // FIXME UNICODE
367         docstring const counter = from_ascii(fl.type());
368         docstring const label = from_utf8(fl.name());
369
370         ParagraphList::iterator p = pars.begin();
371         for (; p != pars.end(); ++p) {
372                 InsetList::iterator it2 = p->insetlist.begin();
373                 InsetList::iterator end2 = p->insetlist.end();
374                 // Any caption within this float should have the same
375                 // label prefix but different numbers.
376                 for (; it2 != end2; ++it2) {
377                         InsetBase & icap = *it2->inset;
378                         // Look deeper just in case.
379                         setCaptionLabels(icap, fl, counters);
380                         if (icap.lyxCode() == InsetBase::CAPTION_CODE) {
381                                 // We found a caption!
382                                 counters.step(counter); 
383                                 int number = counters.value(counter);
384                                 static_cast<InsetCaption &>(icap).setCount(number);
385                                 static_cast<InsetCaption &>(icap).setLabel(label);
386                         }
387                 }
388         }
389 }
390
391
392 void setCaptions(Paragraph & par, LyXTextClass const & textclass)
393 {
394         if (par.insetlist.empty())
395                 return;
396
397         Counters & counters = textclass.counters();
398
399         InsetList::iterator it = par.insetlist.begin();
400         InsetList::iterator end = par.insetlist.end();
401         for (; it != end; ++it) {
402                 InsetBase & inset = *it->inset;
403                 if (inset.lyxCode() != InsetBase::FLOAT_CODE 
404                         && inset.lyxCode() != InsetBase::WRAP_CODE)
405                         continue;
406
407                 docstring const & type = inset.getInsetName();
408                 if (type.empty())
409                         continue;
410
411                 Floating const & fl = textclass.floats().getType(to_ascii(type));
412                 setCaptionLabels(inset, fl, counters);
413         }
414 }
415
416 // set the label of a paragraph. This includes the counters.
417 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
418 {
419         Paragraph & par = *it;
420         LyXLayout_ptr const & layout = par.layout();
421         Counters & counters = textclass.counters();
422
423         if (it.pit() == 0) {
424                 par.params().appendix(par.params().startOfAppendix());
425         } else {
426                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
427                 if (!par.params().appendix() &&
428                     par.params().startOfAppendix()) {
429                         par.params().appendix(true);
430                         textclass.counters().reset();
431                 }
432         }
433
434         // Compute the item depth of the paragraph
435         par.itemdepth = getItemDepth(it);
436
437         if (layout->margintype == MARGIN_MANUAL) {
438                 if (par.params().labelWidthString().empty())
439                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
440         } else {
441                 par.params().labelWidthString(docstring());
442         }
443
444         // Optimisation: setLabel() can be called for each for each
445         // paragraph of the document. So we make the string static to
446         // avoid the repeated instanciation.
447         static docstring itemlabel;
448
449         // is it a layout that has an automatic label?
450         if (layout->labeltype == LABEL_COUNTER) {
451                 if (layout->toclevel <= buf.params().secnumdepth
452                     && (layout->latextype != LATEX_ENVIRONMENT
453                         || isFirstInSequence(it.pit(), it.plist()))) {
454                         counters.step(layout->counter);
455                         par.params().labelString(
456                                 par.expandLabel(layout, buf.params()));
457                 } else
458                         par.params().labelString(docstring());
459
460         } else if (layout->labeltype == LABEL_ITEMIZE) {
461                 // At some point of time we should do something more
462                 // clever here, like:
463                 //   par.params().labelString(
464                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
465                 // for now, use a simple hardcoded label
466                 switch (par.itemdepth) {
467                 case 0:
468                         itemlabel = char_type(0x2022);
469                         break;
470                 case 1:
471                         itemlabel = char_type(0x2013);
472                         break;
473                 case 2:
474                         itemlabel = char_type(0x2217);
475                         break;
476                 case 3:
477                         itemlabel = char_type(0x2219); // or 0x00b7
478                         break;
479                 }
480                 par.params().labelString(itemlabel);
481
482         } else if (layout->labeltype == LABEL_ENUMERATE) {
483                 // FIXME
484                 // Yes I know this is a really, really! bad solution
485                 // (Lgb)
486                 docstring enumcounter = from_ascii("enum");
487
488                 switch (par.itemdepth) {
489                 case 2:
490                         enumcounter += 'i';
491                 case 1:
492                         enumcounter += 'i';
493                 case 0:
494                         enumcounter += 'i';
495                         break;
496                 case 3:
497                         enumcounter += "iv";
498                         break;
499                 default:
500                         // not a valid enumdepth...
501                         break;
502                 }
503
504                 // Maybe we have to reset the enumeration counter.
505                 if (needEnumCounterReset(it))
506                         counters.reset(enumcounter);
507
508                 counters.step(enumcounter);
509
510                 string format;
511
512                 switch (par.itemdepth) {
513                 case 0:
514                         format = N_("\\arabic{enumi}.");
515                         break;
516                 case 1:
517                         format = N_("(\\alph{enumii})");
518                         break;
519                 case 2:
520                         format = N_("\\roman{enumiii}.");
521                         break;
522                 case 3:
523                         format = N_("\\Alph{enumiv}.");
524                         break;
525                 default:
526                         // not a valid enumdepth...
527                         break;
528                 }
529
530                 par.params().labelString(counters.counterLabel(
531                         par.translateIfPossible(from_ascii(format), buf.params())));
532
533         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
534                 counters.step(from_ascii("bibitem"));
535                 int number = counters.value(from_ascii("bibitem"));
536                 if (par.bibitem())
537                         par.bibitem()->setCounter(number);
538
539                 par.params().labelString(
540                         par.translateIfPossible(layout->labelstring(), buf.params()));
541                 // In biblio shouldn't be following counters but...
542         } else if (layout->labeltype == LABEL_SENSITIVE) {
543                 // Search for the first float or wrap inset in the iterator
544                 size_t i = it.depth();
545                 InsetBase * in;
546                 while (i > 0) {
547                         --i;
548                         in = &it[i].inset();
549                         if (in->lyxCode() == InsetBase::FLOAT_CODE
550                             || in->lyxCode() == InsetBase::WRAP_CODE)
551                                 break;
552                 }
553                 docstring const & type = in->getInsetName();
554
555                 if (!type.empty()) {
556                         Floating const & fl = textclass.floats().getType(to_ascii(type));
557                         // FIXME UNICODE
558                         counters.step(from_ascii(fl.type()));
559
560                         // Doesn't work... yet.
561                         par.params().labelString(par.translateIfPossible(
562                                 bformat(from_ascii("%1$s #:"), from_utf8(fl.name())),
563                                 buf.params()));
564                 } else {
565                         // par->SetLayout(0);
566                         par.params().labelString(par.translateIfPossible(
567                                 layout->labelstring(), buf.params()));
568                 }
569
570         } else if (layout->labeltype == LABEL_NO_LABEL)
571                 par.params().labelString(docstring());
572         else
573                 par.params().labelString(
574                         par.translateIfPossible(layout->labelstring(), buf.params()));
575 }
576
577 } // anon namespace
578
579
580 bool updateCurrentLabel(Buffer const & buf,
581         ParIterator & it)
582 {
583     if (it == par_iterator_end(buf.inset()))
584         return false;
585
586 //      if (it.lastpit == 0 && LyXText::isMainText(buf))
587 //              return false;
588
589         switch (it->layout()->labeltype) {
590
591         case LABEL_NO_LABEL:
592         case LABEL_MANUAL:
593         case LABEL_BIBLIO:
594         case LABEL_TOP_ENVIRONMENT:
595         case LABEL_CENTERED_TOP_ENVIRONMENT:
596         case LABEL_STATIC:
597         case LABEL_ITEMIZE:
598                 setLabel(buf, it, buf.params().getLyXTextClass());
599                 return true;
600
601         case LABEL_SENSITIVE:
602         case LABEL_COUNTER:
603         // do more things with enumerate later
604         case LABEL_ENUMERATE:
605                 return false;
606         }
607
608         // This is dead code which get rid of a warning:
609         return true;
610 }
611
612
613 void updateLabels(Buffer const & buf,
614         ParIterator & from, ParIterator & to, bool childonly)
615 {
616         for (ParIterator it = from; it != to; ++it) {
617                 if (it.pit() > it.lastpit())
618                         return;
619                 if (!updateCurrentLabel (buf, it)) {
620                         updateLabels(buf, childonly);
621                         return;
622                 }
623         }
624 }
625
626
627 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
628 {
629         if (updateCurrentLabel(buf, iter))
630                 return;
631
632         updateLabels(buf, childonly);
633 }
634
635
636 void updateLabels(Buffer const & buf, bool childonly)
637 {
638         // Use the master text class also for child documents
639         LyXTextClass const & textclass = buf.params().getLyXTextClass();
640
641         if (!childonly) {
642                 // If this is a child document start with the master
643                 Buffer const * const master = buf.getMasterBuffer();
644                 if (master != &buf) {
645                         updateLabels(*master);
646                         return;
647                 }
648
649                 // start over the counters
650                 textclass.counters().reset();
651         }
652
653         ParIterator const end = par_iterator_end(buf.inset());
654
655         for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
656                 // reduce depth if necessary
657                 if (it.pit()) {
658                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
659                         it->params().depth(min(it->params().depth(),
660                                                prevpar.getMaxDepthAfter()));
661                 } else
662                         it->params().depth(0);
663
664                 // set the counter for this paragraph
665                 setLabel(buf, it, textclass);
666
667                 // It is better to set the captions after setLabel because
668                 // the caption number might need the section number in the
669                 // future.
670                 setCaptions(*it, textclass);
671
672                 // Now included docs
673                 InsetList::const_iterator iit = it->insetlist.begin();
674                 InsetList::const_iterator end = it->insetlist.end();
675                 for (; iit != end; ++iit) {
676                         if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
677                                 static_cast<InsetInclude const *>(iit->inset)
678                                         ->updateLabels(buf);
679                 }
680         }
681
682         const_cast<Buffer &>(buf).tocBackend().update();
683 }
684
685
686 } // namespace lyx