]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
add a \unbind keyword and a few utility functions (unbind, write, delkey) to KeyMap...
[lyx.git] / src / buffer_funcs.cpp
1 /**
2  * \file buffer_funcs.cpp
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 "debug.h"
20 #include "DocIterator.h"
21 #include "Counters.h"
22 #include "ErrorList.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "LaTeX.h"
30 #include "Layout.h"
31 #include "LyX.h"
32 #include "lyxlayout_ptr_fwd.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "LyXVC.h"
41 #include "TexRow.h"
42 #include "Text.h"
43 #include "TocBackend.h"
44 #include "VCBackend.h"
45
46 #include "frontends/alert.h"
47
48 #include "insets/InsetBibitem.h"
49 #include "insets/InsetInclude.h"
50
51 #include "support/filetools.h"
52 #include "support/fs_extras.h"
53 #include "support/lyxlib.h"
54
55 #include <boost/bind.hpp>
56
57 using std::min;
58 using std::string;
59
60
61 namespace lyx {
62
63 using namespace std;
64
65 using support::bformat;
66 using support::FileName;
67 using support::libFileSearch;
68 using support::makeAbsPath;
69 using support::makeDisplayPath;
70 using support::onlyFilename;
71 using support::onlyPath;
72 using support::unlink;
73
74 namespace Alert = frontend::Alert;
75
76 namespace {
77
78 bool readFile(Buffer * const b, FileName const & s)
79 {
80         BOOST_ASSERT(b);
81
82         // File information about normal file
83         if (!s.exists()) {
84                 docstring const file = makeDisplayPath(s.absFilename(), 50);
85                 docstring text = bformat(_("The specified document\n%1$s"
86                                                      "\ncould not be read."), file);
87                 Alert::error(_("Could not read document"), text);
88                 return false;
89         }
90
91         // Check if emergency save file exists and is newer.
92         FileName const e(s.absFilename() + ".emergency");
93
94         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
95                 docstring const file = makeDisplayPath(s.absFilename(), 20);
96                 docstring const text =
97                         bformat(_("An emergency save of the document "
98                                   "%1$s exists.\n\n"
99                                                "Recover emergency save?"), file);
100                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
101                                       _("&Recover"),  _("&Load Original"),
102                                       _("&Cancel")))
103                 {
104                 case 0:
105                         // the file is not saved if we load the emergency file.
106                         b->markDirty();
107                         return b->readFile(e);
108                 case 1:
109                         break;
110                 default:
111                         return false;
112                 }
113         }
114
115         // Now check if autosave file is newer.
116         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
117
118         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
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 (s.isReadable()) {
153                 if (readFile(b, s)) {
154                         b->lyxvc().file_found_hook(s);
155                         if (!s.isWritable())
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
182 bool checkIfLoaded(FileName const & fn)
183 {
184         return theBufferList().getBuffer(fn.absFilename());
185 }
186
187
188 Buffer * checkAndLoadLyXFile(FileName const & filename)
189 {
190         // File already open?
191         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
192         if (checkBuffer) {
193                 if (checkBuffer->isClean())
194                         return checkBuffer;
195                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
196                 docstring text = bformat(_(
197                                 "The document %1$s is already loaded and has unsaved changes.\n"
198                                 "Do you want to abandon your changes and reload the version on disk?"), file);
199                 if (Alert::prompt(_("Reload saved document?"),
200                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
201                         return checkBuffer;
202
203                 // FIXME: should be LFUN_REVERT
204                 if (theBufferList().close(checkBuffer, false))
205                         // Load it again.
206                         return checkAndLoadLyXFile(filename);
207                 else
208                         // The file could not be closed.
209                         return 0;
210         }
211
212         if (filename.isReadable()) {
213                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
214                 if (!lyx::loadLyXFile(b, filename)) {
215                         theBufferList().release(b);
216                         return 0;
217                 }
218                 return b;
219         }
220
221         docstring text = bformat(_("The document %1$s does not yet "
222                 "exist.\n\nDo you want to create a new document?"),
223                 from_utf8(filename.absFilename()));
224         if (!Alert::prompt(_("Create new document?"),
225                         text, 0, 1, _("&Create"), _("Cancel")))
226                 return newFile(filename.absFilename(), string(), true);
227
228         return 0;
229 }
230
231 // FIXME newFile() should probably be a member method of Application...
232 Buffer * newFile(string const & filename, string const & templatename,
233                  bool const isNamed)
234 {
235         // get a free buffer
236         Buffer * b = theBufferList().newBuffer(filename);
237         BOOST_ASSERT(b);
238
239         FileName tname;
240         // use defaults.lyx as a default template if it exists.
241         if (templatename.empty())
242                 tname = libFileSearch("templates", "defaults.lyx");
243         else
244                 tname = makeAbsPath(templatename);
245
246         if (!tname.empty()) {
247                 if (!b->readFile(tname)) {
248                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
249                         docstring const text  = bformat(
250                                 _("The specified document template\n%1$s\ncould not be read."),
251                                 file);
252                         Alert::error(_("Could not read template"), text);
253                         theBufferList().release(b);
254                         return 0;
255                 }
256         }
257
258         if (!isNamed) {
259                 b->setUnnamed();
260                 b->setFileName(filename);
261         }
262
263         b->setReadonly(false);
264         b->setFullyLoaded(true);
265
266         return b;
267 }
268
269
270 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
271                                   ErrorList & errorList)
272 {
273         TeXErrors::Errors::const_iterator cit = terr.begin();
274         TeXErrors::Errors::const_iterator end = terr.end();
275
276         for (; cit != end; ++cit) {
277                 int id_start = -1;
278                 int pos_start = -1;
279                 int errorrow = cit->error_in_line;
280                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
281                                                        pos_start);
282                 int id_end = -1;
283                 int pos_end = -1;
284                 do {
285                         ++errorrow;
286                         found = buf.texrow().getIdFromRow(errorrow, id_end,
287                                                           pos_end);
288                 } while (found && id_start == id_end && pos_start == pos_end);
289
290                 errorList.push_back(ErrorItem(cit->error_desc,
291                         cit->error_text, id_start, pos_start, pos_end));
292         }
293 }
294
295
296 int countWords(DocIterator const & from, DocIterator const & to)
297 {
298         int count = 0;
299         bool inword = false;
300         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
301                 // Copied and adapted from isLetter() in ControlSpellChecker
302                 if (dit.inTexted()
303                     && dit.pos() != dit.lastpos()
304                     && dit.paragraph().isLetter(dit.pos())
305                     && !dit.paragraph().isDeleted(dit.pos())) {
306                         if (!inword) {
307                                 ++count;
308                                 inword = true;
309                         }
310                 } else if (inword)
311                         inword = false;
312         }
313
314         return count;
315 }
316
317
318 namespace {
319
320 depth_type getDepth(DocIterator const & it)
321 {
322         depth_type depth = 0;
323         for (size_t i = 0 ; i < it.depth() ; ++i)
324                 if (!it[i].inset().inMathed())
325                         depth += it[i].paragraph().getDepth() + 1;
326         // remove 1 since the outer inset does not count
327         return depth - 1;
328 }
329
330 depth_type getItemDepth(ParIterator const & it)
331 {
332         Paragraph const & par = *it;
333         LabelType const labeltype = par.layout()->labeltype;
334
335         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
336                 return 0;
337
338         // this will hold the lowest depth encountered up to now.
339         depth_type min_depth = getDepth(it);
340         ParIterator prev_it = it;
341         while (true) {
342                 if (prev_it.pit())
343                         --prev_it.top().pit();
344                 else {
345                         // start of nested inset: go to outer par
346                         prev_it.pop_back();
347                         if (prev_it.empty()) {
348                                 // start of document: nothing to do
349                                 return 0;
350                         }
351                 }
352
353                 // We search for the first paragraph with same label
354                 // that is not more deeply nested.
355                 Paragraph & prev_par = *prev_it;
356                 depth_type const prev_depth = getDepth(prev_it);
357                 if (labeltype == prev_par.layout()->labeltype) {
358                         if (prev_depth < min_depth) {
359                                 return prev_par.itemdepth + 1;
360                         }
361                         else if (prev_depth == min_depth) {
362                                 return prev_par.itemdepth;
363                         }
364                 }
365                 min_depth = std::min(min_depth, prev_depth);
366                 // small optimization: if we are at depth 0, we won't
367                 // find anything else
368                 if (prev_depth == 0) {
369                         return 0;
370                 }
371         }
372 }
373
374
375 bool needEnumCounterReset(ParIterator const & it)
376 {
377         Paragraph const & par = *it;
378         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
379         depth_type const cur_depth = par.getDepth();
380         ParIterator prev_it = it;
381         while (prev_it.pit()) {
382                 --prev_it.top().pit();
383                 Paragraph const & prev_par = *prev_it;
384                 if (prev_par.getDepth() <= cur_depth)
385                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
386         }
387         // start of nested inset: reset
388         return true;
389 }
390
391
392 // set the label of a paragraph. This includes the counters.
393 void setLabel(Buffer const & buf, ParIterator & it)
394 {
395         TextClass const & textclass = buf.params().getTextClass();
396         Paragraph & par = it.paragraph();
397         LayoutPtr const & layout = par.layout();
398         Counters & counters = textclass.counters();
399
400         if (par.params().startOfAppendix()) {
401                 // FIXME: only the counter corresponding to toplevel
402                 // sectionning should be reset
403                 counters.reset();
404                 counters.appendix(true);
405         }
406         par.params().appendix(counters.appendix());
407
408         // Compute the item depth of the paragraph
409         par.itemdepth = getItemDepth(it);
410
411         if (layout->margintype == MARGIN_MANUAL) {
412                 if (par.params().labelWidthString().empty())
413                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
414         } else {
415                 par.params().labelWidthString(docstring());
416         }
417
418         switch(layout->labeltype) {
419         case LABEL_COUNTER:
420                 if (layout->toclevel <= buf.params().secnumdepth
421                     && (layout->latextype != LATEX_ENVIRONMENT
422                         || isFirstInSequence(it.pit(), it.plist()))) {
423                         counters.step(layout->counter);
424                         par.params().labelString(
425                                 par.expandLabel(layout, buf.params()));
426                 } else
427                         par.params().labelString(docstring());
428                 break;
429
430         case LABEL_ITEMIZE: {
431                 // At some point of time we should do something more
432                 // clever here, like:
433                 //   par.params().labelString(
434                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
435                 // for now, use a simple hardcoded label
436                 docstring itemlabel;
437                 switch (par.itemdepth) {
438                 case 0:
439                         itemlabel = char_type(0x2022);
440                         break;
441                 case 1:
442                         itemlabel = char_type(0x2013);
443                         break;
444                 case 2:
445                         itemlabel = char_type(0x2217);
446                         break;
447                 case 3:
448                         itemlabel = char_type(0x2219); // or 0x00b7
449                         break;
450                 }
451                 par.params().labelString(itemlabel);
452                 break;
453         }
454
455         case LABEL_ENUMERATE: {
456                 // FIXME: Yes I know this is a really, really! bad solution
457                 // (Lgb)
458                 docstring enumcounter = from_ascii("enum");
459
460                 switch (par.itemdepth) {
461                 case 2:
462                         enumcounter += 'i';
463                 case 1:
464                         enumcounter += 'i';
465                 case 0:
466                         enumcounter += 'i';
467                         break;
468                 case 3:
469                         enumcounter += "iv";
470                         break;
471                 default:
472                         // not a valid enumdepth...
473                         break;
474                 }
475
476                 // Maybe we have to reset the enumeration counter.
477                 if (needEnumCounterReset(it))
478                         counters.reset(enumcounter);
479
480                 counters.step(enumcounter);
481
482                 string format;
483
484                 switch (par.itemdepth) {
485                 case 0:
486                         format = N_("\\arabic{enumi}.");
487                         break;
488                 case 1:
489                         format = N_("(\\alph{enumii})");
490                         break;
491                 case 2:
492                         format = N_("\\roman{enumiii}.");
493                         break;
494                 case 3:
495                         format = N_("\\Alph{enumiv}.");
496                         break;
497                 default:
498                         // not a valid enumdepth...
499                         break;
500                 }
501
502                 par.params().labelString(counters.counterLabel(
503                         par.translateIfPossible(from_ascii(format), buf.params())));
504
505                 break;
506         }
507
508         case LABEL_SENSITIVE: {
509                 string const & type = counters.current_float();
510                 docstring full_label;
511                 if (type.empty())
512                         full_label = buf.B_("Senseless!!! ");
513                 else {
514                         docstring name = buf.B_(textclass.floats().getType(type).name());
515                         if (counters.hasCounter(from_utf8(type))) {
516                                 counters.step(from_utf8(type));
517                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
518                                                      name, 
519                                                      counters.theCounter(from_utf8(type)));
520                         } else
521                                 full_label = bformat(from_ascii("%1$s #:"), name);      
522                 }
523                 par.params().labelString(full_label);   
524                 break;
525         }
526
527         case LABEL_NO_LABEL:
528                 par.params().labelString(docstring());
529                 break;
530
531         case LABEL_MANUAL:
532         case LABEL_TOP_ENVIRONMENT:
533         case LABEL_CENTERED_TOP_ENVIRONMENT:
534         case LABEL_STATIC:      
535         case LABEL_BIBLIO:
536                 par.params().labelString(
537                         par.translateIfPossible(layout->labelstring(), 
538                                                 buf.params()));
539                 break;
540         }
541 }
542
543 } // anon namespace
544
545 void updateLabels(Buffer const & buf, ParIterator & parit)
546 {
547         BOOST_ASSERT(parit.pit() == 0);
548
549         depth_type maxdepth = 0;
550         pit_type const lastpit = parit.lastpit();
551         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
552                 // reduce depth if necessary
553                 parit->params().depth(min(parit->params().depth(), maxdepth));
554                 maxdepth = parit->getMaxDepthAfter();
555
556                 // set the counter for this paragraph
557                 setLabel(buf, parit);
558
559                 // Now the insets
560                 InsetList::const_iterator iit = parit->insetList().begin();
561                 InsetList::const_iterator end = parit->insetList().end();
562                 for (; iit != end; ++iit) {
563                         parit.pos() = iit->pos;
564                         iit->inset->updateLabels(buf, parit);
565                 }
566         }
567         
568 }
569
570
571 // FIXME: buf should should be const because updateLabels() modifies
572 // the contents of the paragraphs.
573 void updateLabels(Buffer const & buf, bool childonly)
574 {
575         Buffer const * const master = buf.masterBuffer();
576         // Use the master text class also for child documents
577         TextClass const & textclass = master->params().getTextClass();
578
579         if (!childonly) {
580                 // If this is a child document start with the master
581                 if (master != &buf) {
582                         updateLabels(*master);
583                         return;
584                 }
585
586                 // start over the counters
587                 textclass.counters().reset();
588         }
589
590         Buffer & cbuf = const_cast<Buffer &>(buf);
591
592         if (buf.text().empty()) {
593                 // FIXME: we don't call continue with updateLabels()
594                 // here because it crashes on newly created documents.
595                 // But the TocBackend needs to be initialised
596                 // nonetheless so we update the tocBackend manually.
597                 cbuf.tocBackend().update();
598                 return;
599         }
600
601         // do the real work
602         ParIterator parit = par_iterator_begin(buf.inset());
603         updateLabels(buf, parit);
604
605         cbuf.tocBackend().update();
606         if (!childonly)
607                 cbuf.structureChanged();
608         // FIXME
609         // the embedding signal is emitted with structureChanged signal
610         // this is inaccurate so these two will be separated later.
611         //cbuf.embeddedFiles().update();
612         //cbuf.embeddingChanged();
613 }
614
615
616 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
617 {
618         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
619                 Buffer * master = buffer.masterBuffer();
620                 master->tocBackend().updateItem(par_it);
621                 master->structureChanged();
622         }
623 }
624
625
626 textclass_type defaultTextclass()
627 {
628         // We want to return the article class. if `first' is
629         // true in the returned pair, then `second' is the textclass
630         // number; if it is false, second is 0. In both cases, second
631         // is what we want.
632         return textclasslist.numberOfClass("article").second;
633 }
634
635 } // namespace lyx