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