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