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