]> git.lyx.org Git - lyx.git/blob - src/buffer.C
ebf5700814ab863aaa5a863e823595ddc48165a7
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "bufferlist.h"
15 #include "LyXAction.h"
16 #include "lyxrc.h"
17 #include "lyxlex.h"
18 #include "tex-strings.h"
19 #include "layout.h"
20 #include "bufferview_funcs.h"
21 #include "lyxfont.h"
22 #include "version.h"
23 #include "LaTeX.h"
24 #include "Chktex.h"
25 #include "debug.h"
26 #include "LaTeXFeatures.h"
27 #include "lyxtext.h"
28 #include "gettext.h"
29 #include "language.h"
30 #include "exporter.h"
31 #include "Lsstream.h"
32 #include "format.h"
33 #include "BufferView.h"
34 #include "ParagraphParameters.h"
35 #include "iterators.h"
36 #include "lyxtextclasslist.h"
37 #include "sgml.h"
38 #include "paragraph_funcs.h"
39 #include "messages.h"
40 #include "author.h"
41
42 #include "frontends/LyXView.h"
43
44 #include "mathed/formulamacro.h"
45 #include "mathed/formula.h"
46
47 #include "insets/inseterror.h"
48 #include "insets/insetbibitem.h"
49 #include "insets/insetbibtex.h"
50 #include "insets/insetinclude.h"
51 #include "insets/insettext.h"
52
53 #include "frontends/Dialogs.h"
54 #include "frontends/Alert.h"
55
56 #include "graphics/Previews.h"
57
58 #include "support/textutils.h"
59 #include "support/filetools.h"
60 #include "support/path.h"
61 #include "support/os.h"
62 #include "support/lyxlib.h"
63 #include "support/FileInfo.h"
64 #include "support/lyxmanip.h"
65 #include "support/lyxtime.h"
66
67 #include <boost/bind.hpp>
68 #include <boost/tuple/tuple.hpp>
69 #include "support/BoostFormat.h"
70
71 #include <fstream>
72 #include <iomanip>
73 #include <map>
74 #include <stack>
75 #include <list>
76 #include <algorithm>
77
78 #include <cstdlib>
79 #include <cmath>
80 #include <unistd.h>
81 #include <sys/types.h>
82 #include <utime.h>
83
84 #ifdef HAVE_LOCALE
85 #include <locale>
86 #endif
87
88 #ifndef CXX_GLOBAL_CSTD
89 using std::pow;
90 #endif
91
92 using std::ostream;
93 using std::ofstream;
94 using std::ifstream;
95 using std::fstream;
96 using std::ios;
97 using std::setw;
98 using std::endl;
99 using std::pair;
100 using std::make_pair;
101 using std::vector;
102 using std::map;
103 using std::stack;
104 using std::list;
105 using std::for_each;
106
107 using lyx::pos_type;
108 using lyx::textclass_type;
109
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
112
113 namespace {
114
115 const int LYX_FORMAT = 223;
116
117 } // namespace anon
118
119 Buffer::Buffer(string const & file, bool ronly)
120         : niceFile(true), lyx_clean(true), bak_clean(true),
121           unnamed(false), read_only(ronly),
122           filename_(file), users(0)
123 {
124         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
125         filepath_ = OnlyPath(file);
126         lyxvc.buffer(this);
127         if (read_only || lyxrc.use_tempdir) {
128                 tmppath = CreateBufferTmpDir();
129         } else {
130                 tmppath.erase();
131         }
132
133         // set initial author
134         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
135 }
136
137
138 Buffer::~Buffer()
139 {
140         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
141         // here the buffer should take care that it is
142         // saved properly, before it goes into the void.
143
144         // make sure that views using this buffer
145         // forgets it.
146         if (users)
147                 users->buffer(0);
148
149         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
150 #if USE_BOOST_FORMAT
151                 boost::format fmt = _("Could not remove the temporary directory %1$s");
152                 fmt % tmppath;
153                 string msg = fmt.str();
154 #else
155                 string msg = _("Could not remove the temporary directory ") + tmppath;
156 #endif
157                 Alert::warning(_("Could not remove temporary directory"), msg);
158         }
159
160         paragraphs.clear();
161
162         // Remove any previewed LaTeX snippets assocoated with this buffer.
163         grfx::Previews::get().removeLoader(this);
164 }
165
166
167 string const Buffer::getLatexName(bool no_path) const
168 {
169         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
170         if (no_path)
171                 return OnlyFilename(name);
172         else
173                 return name;
174 }
175
176
177 pair<Buffer::LogType, string> const Buffer::getLogName() const
178 {
179         string const filename = getLatexName(false);
180
181         if (filename.empty())
182                 return make_pair(Buffer::latexlog, string());
183
184         string path = OnlyPath(filename);
185
186         if (lyxrc.use_tempdir || !IsDirWriteable(path))
187                 path = tmppath;
188
189         string const fname = AddName(path,
190                                      OnlyFilename(ChangeExtension(filename,
191                                                                   ".log")));
192         string const bname =
193                 AddName(path, OnlyFilename(
194                         ChangeExtension(filename,
195                                         formats.extension("literate") + ".out")));
196
197         // If no Latex log or Build log is newer, show Build log
198
199         FileInfo const f_fi(fname);
200         FileInfo const b_fi(bname);
201
202         if (b_fi.exist() &&
203             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
204                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
205                 return make_pair(Buffer::buildlog, bname);
206         }
207         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
208         return make_pair(Buffer::latexlog, fname);
209 }
210
211
212 void Buffer::setReadonly(bool flag)
213 {
214         if (read_only != flag) {
215                 read_only = flag;
216                 updateTitles();
217                 users->owner()->getDialogs().updateBufferDependent(false);
218         }
219 }
220
221
222 AuthorList & Buffer::authors()
223 {
224         return params.authorlist;
225 }
226
227
228 /// Update window titles of all users
229 // Should work on a list
230 void Buffer::updateTitles() const
231 {
232         if (users)
233                 users->owner()->updateWindowTitle();
234 }
235
236
237 /// Reset autosave timer of all users
238 // Should work on a list
239 void Buffer::resetAutosaveTimers() const
240 {
241         if (users)
242                 users->owner()->resetAutosaveTimer();
243 }
244
245
246 void Buffer::setFileName(string const & newfile)
247 {
248         filename_ = MakeAbsPath(newfile);
249         filepath_ = OnlyPath(filename_);
250         setReadonly(IsFileWriteable(filename_) == 0);
251         updateTitles();
252 }
253
254
255 // We'll remove this later. (Lgb)
256 namespace {
257
258 void unknownClass(string const & unknown)
259 {
260         string msg =
261 #if USE_BOOST_FORMAT
262                 boost::io::str(boost::format(
263                         _("Using the default document class, because the "
264                         " class %1$s is unknown.")) % unknown);
265 #else
266                 _("Using the default document class, because the "
267                 " class ") + unknown + (" is unknown.");
268 #endif
269         Alert::warning(_("Unknown document class"), msg);
270 }
271
272 } // anon
273
274 int Buffer::readHeader(LyXLex & lex)
275 {
276         int unknown_tokens = 0;
277
278         while (lex.isOK()) {
279                 lex.nextToken();
280                 string const token = lex.getString();
281
282                 if (token.empty())
283                         continue;
284
285                 if (token == "\\end_header")
286                         break;
287
288                 lyxerr[Debug::PARSER] << "Handling header token: `"
289                                       << token << '\'' << endl;
290
291                 string unknown = params.readToken(lex, token);
292                 if (!unknown.empty()) {
293                         if (unknown[0] != '\\') {
294                                 unknownClass(unknown);
295                         } else {
296                                 ++unknown_tokens;
297                         }
298                 }
299         }
300         return unknown_tokens;
301 }
302
303
304 // candidate for move to BufferView
305 // (at least some parts in the beginning of the func)
306 //
307 // Uwe C. Schroeder
308 // changed to be public and have one parameter
309 // if par = 0 normal behavior
310 // else insert behavior
311 // Returns false if "\the_end" is not read (Asger)
312 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
313 {
314         int unknown_tokens = 0;
315
316         Paragraph::depth_type depth = 0;
317         bool the_end_read = false;
318
319         if (paragraphs.empty()) {
320                 unknown_tokens += readHeader(lex);
321
322                 if (!params.getLyXTextClass().load()) {
323                         string theclass = params.getLyXTextClass().name();
324                         string msg =
325 #if USE_BOOST_FORMAT
326                                 boost::io::str(boost::format(
327                                         _("Using the default document class, because the "
328                                         " class %1$s could not be loaded.")) % theclass);
329 #else
330                                 _("Using the default document class, because the "
331                                 " class ") + theclass + (" could not be loaded.");
332 #endif
333                         Alert::error(_("Can't load document class"), msg);
334                         params.textclass = 0;
335                 }
336         } else {
337                 // We are inserting into an existing document
338                 users->text->breakParagraph(paragraphs);
339
340                 // We don't want to adopt the parameters from the
341                 // document we insert, so read them into a temporary buffer
342                 // and then discard it
343
344                 Buffer tmpbuf("", false);
345                 tmpbuf.readHeader(lex);
346         }
347
348         while (lex.isOK()) {
349                 lex.nextToken();
350                 string const token = lex.getString();
351
352                 if (token.empty())
353                         continue;
354
355                 lyxerr[Debug::PARSER] << "Handling token: `"
356                                       << token << '\'' << endl;
357
358                 if (token == "\\the_end") {
359                         the_end_read = true;
360                         continue;
361                 }
362
363                 unknown_tokens += readParagraph(lex, token, paragraphs, pit, depth);
364         }
365
366
367         if (unknown_tokens > 0) {
368 #if USE_BOOST_FORMAT
369                 string s;
370                 if (unknown_tokens == 1) {
371                         boost::format fmt(_("Encountered one unknown token when reading the document %1$s."));
372                         fmt % fileName();
373                         s = fmt.str();
374                 } else {
375                         boost::format fmt(_("Encountered %1$s unknown tokens when reading the document %2$s."));
376                         fmt % tostr(unknown_tokens);
377                         fmt % fileName();
378                         s = fmt.str();
379                 }
380 #else
381                 string s = _("Encountered ");
382                 if (unknown_tokens == 1) {
383                         s += _("one unknown token");
384                 } else {
385                         s += tostr(unknown_tokens);
386                         s += _(" unknown tokens");
387                 }
388                 Alert::warning(_("Document format failure"), s);
389 #endif
390         }
391
392         return the_end_read;
393 }
394
395
396 int
397 Buffer::readParagraph(LyXLex & lex, string const & token,
398                       ParagraphList & pars, ParagraphList::iterator & pit,
399                       Paragraph::depth_type & depth)
400 {
401         static Change current_change;
402         int unknown = 0;
403
404         if (token == "\\layout") {
405                 lex.pushToken(token);
406
407                 Paragraph * par = new Paragraph();
408                 par->params().depth(depth);
409                 if (params.tracking_changes)
410                         par->trackChanges();
411                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
412                 par->setFont(0, f);
413
414                 // FIXME: goddamn InsetTabular makes us pass a Buffer
415                 // not BufferParams
416                 unknown += ::readParagraph(*this, *par, lex);
417
418                 // insert after
419                 if (pit != pars.end())
420                         ++pit;
421                 pit = pars.insert(pit, par);
422         } else if (token == "\\begin_deeper") {
423                 ++depth;
424         } else if (token == "\\end_deeper") {
425                 if (!depth) {
426                         lex.printError("\\end_deeper: " "depth is already null");
427                 } else {
428                         --depth;
429                 }
430         } else {
431                 ++unknown;
432         }
433         return unknown;
434 }
435
436
437 // needed to insert the selection
438 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
439                                  LyXFont const & fn,string const & str)
440 {
441         LyXLayout_ptr const & layout = par->layout();
442
443         LyXFont font = fn;
444
445         par->checkInsertChar(font);
446         // insert the string, don't insert doublespace
447         bool space_inserted = true;
448         bool autobreakrows = !par->inInset() ||
449                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
450         for(string::const_iterator cit = str.begin();
451             cit != str.end(); ++cit) {
452                 if (*cit == '\n') {
453                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
454                                 breakParagraph(params, paragraphs, par, pos,
455                                                layout->isEnvironment());
456                                 ++par;
457                                 pos = 0;
458                                 space_inserted = true;
459                         } else {
460                                 continue;
461                         }
462                         // do not insert consecutive spaces if !free_spacing
463                 } else if ((*cit == ' ' || *cit == '\t') &&
464                            space_inserted && !layout->free_spacing &&
465                                    !par->isFreeSpacing())
466                 {
467                         continue;
468                 } else if (*cit == '\t') {
469                         if (!layout->free_spacing && !par->isFreeSpacing()) {
470                                 // tabs are like spaces here
471                                 par->insertChar(pos, ' ', font);
472                                 ++pos;
473                                 space_inserted = true;
474                         } else {
475                                 const pos_type nb = 8 - pos % 8;
476                                 for (pos_type a = 0; a < nb ; ++a) {
477                                         par->insertChar(pos, ' ', font);
478                                         ++pos;
479                                 }
480                                 space_inserted = true;
481                         }
482                 } else if (!IsPrintable(*cit)) {
483                         // Ignore unprintables
484                         continue;
485                 } else {
486                         // just insert the character
487                         par->insertChar(pos, *cit, font);
488                         ++pos;
489                         space_inserted = (*cit == ' ');
490                 }
491
492         }
493 }
494
495
496 bool Buffer::readFile(LyXLex & lex, string const & filename)
497 {
498         bool ret = readFile(lex, filename, paragraphs.begin());
499
500         // After we have read a file, we must ensure that the buffer
501         // language is set and used in the gui.
502         // If you know of a better place to put this, please tell me. (Lgb)
503         updateDocLang(params.language);
504
505         return ret;
506 }
507
508
509 // FIXME: all the below Alerts should give the filename..
510 bool Buffer::readFile(LyXLex & lex, string const & filename,
511                       ParagraphList::iterator pit)
512 {
513         if (!lex.isOK()) {
514                 Alert::error(_("Document could not be read"),
515                         _("The specified document could not be read."));
516                 return false;
517         }
518
519         lex.next();
520         string const token(lex.getString());
521
522         if (!lex.isOK()) {
523                 Alert::error(_("Document could not be read"),
524                         _("The specified document could not be read."));
525                 return false;
526         }
527
528         // the first token _must_ be...
529         if (token != "\\lyxformat") {
530                 Alert::error(_("Document format failure"),
531                         _("The specified document is not a LyX document."));
532                 return false;
533         }
534
535         lex.eatLine();
536         string tmp_format = lex.getString();
537         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
538         // if present remove ".," from string.
539         string::size_type dot = tmp_format.find_first_of(".,");
540         //lyxerr << "           dot found at " << dot << endl;
541         if (dot != string::npos)
542                         tmp_format.erase(dot, 1);
543         file_format = strToInt(tmp_format);
544         //lyxerr << "format: " << file_format << endl;
545         if (file_format == LYX_FORMAT) {
546                 // current format
547         } else if (file_format > LYX_FORMAT) {
548                 Alert::warning(_("Document format failure"),
549                         _("This document was created with a newer version of "
550                         "LyX. This is likely to cause problems."));
551         } else if (file_format < LYX_FORMAT) {
552                 // old formats
553                 if (file_format < 200) {
554                         Alert::error(_("Document format failure"),
555                                 _("This LyX document is too old to be read "
556                                 "by this version of LyX. Try LyX 0.10."));
557                         return false;
558                 } else if (!filename.empty()) {
559                         string command =
560                                 LibFileSearch("lyx2lyx", "lyx2lyx");
561                         if (command.empty()) {
562                                 Alert::error(_("Conversion script not found"),
563                                         _("The document is from an earlier version "
564                                           "of LyX, but the conversion script lyx2lyx "
565                                           "could not be found."));
566                                 return false;
567                         }
568                         command += " -t"
569                                 +tostr(LYX_FORMAT) + ' '
570                                 + QuoteName(filename);
571                         lyxerr[Debug::INFO] << "Running '"
572                                             << command << '\''
573                                             << endl;
574                         cmd_ret const ret = RunCommand(command);
575                         if (ret.first) {
576                                 Alert::error(_("Conversion script failed"),
577                                         _("The document is from an earlier version "
578                                           "of LyX, but the lyx2lyx script failed "
579                                           "to convert it."));
580                                 return false;
581                         }
582                         istringstream is(STRCONV(ret.second));
583                         LyXLex tmplex(0, 0);
584                         tmplex.setStream(is);
585                         return readFile(tmplex, string(), pit);
586                 } else {
587                         // This code is reached if lyx2lyx failed (for
588                         // some reason) to change the file format of
589                         // the file.
590                         lyx::Assert(false);
591                         return false;
592                 }
593         }
594         bool the_end = readBody(lex, pit);
595         params.setPaperStuff();
596
597         if (!the_end) {
598                 Alert::error(_("Document format failure"),
599                         _("The document ended unexpectedly, which means "
600                           "that it is probably corrupted."));
601         }
602         return true;
603 }
604
605
606 // Should probably be moved to somewhere else: BufferView? LyXView?
607 bool Buffer::save() const
608 {
609         // We don't need autosaves in the immediate future. (Asger)
610         resetAutosaveTimers();
611
612         // make a backup
613         string s;
614         if (lyxrc.make_backup) {
615                 s = fileName() + '~';
616                 if (!lyxrc.backupdir_path.empty())
617                         s = AddName(lyxrc.backupdir_path,
618                                     subst(os::slashify_path(s),'/','!'));
619
620                 // Rename is the wrong way of making a backup,
621                 // this is the correct way.
622                 /* truss cp fil fil2:
623                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
624                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
625                    open("LyXVC.lyx", O_RDONLY)                     = 3
626                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
627                    fstat(4, 0xEFFFF508)                            = 0
628                    fstat(3, 0xEFFFF508)                            = 0
629                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
630                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
631                    read(3, 0xEFFFD4A0, 8192)                       = 0
632                    close(4)                                        = 0
633                    close(3)                                        = 0
634                    chmod("LyXVC3.lyx", 0100644)                    = 0
635                    lseek(0, 0, SEEK_CUR)                           = 46440
636                    _exit(0)
637                 */
638
639                 // Should probably have some more error checking here.
640                 // Doing it this way, also makes the inodes stay the same.
641                 // This is still not a very good solution, in particular we
642                 // might loose the owner of the backup.
643                 FileInfo finfo(fileName());
644                 if (finfo.exist()) {
645                         mode_t fmode = finfo.getMode();
646                         struct utimbuf times = {
647                                 finfo.getAccessTime(),
648                                 finfo.getModificationTime() };
649
650                         ifstream ifs(fileName().c_str());
651                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
652                         if (ifs && ofs) {
653                                 ofs << ifs.rdbuf();
654                                 ifs.close();
655                                 ofs.close();
656                                 ::chmod(s.c_str(), fmode);
657
658                                 if (::utime(s.c_str(), &times)) {
659                                         lyxerr << "utime error." << endl;
660                                 }
661                         } else {
662                                 lyxerr << "LyX was not able to make "
663                                         "backup copy. Beware." << endl;
664                         }
665                 }
666         }
667
668         if (writeFile(fileName())) {
669                 markClean();
670                 removeAutosaveFile(fileName());
671         } else {
672                 // Saving failed, so backup is not backup
673                 if (lyxrc.make_backup) {
674                         lyx::rename(s, fileName());
675                 }
676                 return false;
677         }
678         return true;
679 }
680
681
682 bool Buffer::writeFile(string const & fname) const
683 {
684         if (read_only && (fname == fileName())) {
685                 return false;
686         }
687
688         FileInfo finfo(fname);
689         if (finfo.exist() && !finfo.writable()) {
690                 return false;
691         }
692
693         ofstream ofs(fname.c_str());
694         if (!ofs) {
695                 return false;
696         }
697
698 #ifdef HAVE_LOCALE
699         // Use the standard "C" locale for file output.
700         ofs.imbue(std::locale::classic());
701 #endif
702
703         // The top of the file should not be written by params.
704
705         // write out a comment in the top of the file
706         ofs << '#' << lyx_docversion
707             << " created this file. For more info see http://www.lyx.org/\n"
708             << "\\lyxformat " << LYX_FORMAT << "\n";
709
710         // now write out the buffer paramters.
711         params.writeFile(ofs);
712
713         ofs << "\\end_header\n";
714
715         Paragraph::depth_type depth = 0;
716
717         // this will write out all the paragraphs
718         // using recursive descent.
719         ParagraphList::iterator pit = paragraphs.begin();
720         ParagraphList::iterator pend = paragraphs.end();
721         for (; pit != pend; ++pit)
722                 pit->write(this, ofs, params, depth);
723
724         // Write marker that shows file is complete
725         ofs << "\n\\the_end" << endl;
726
727         ofs.close();
728
729         // how to check if close went ok?
730         // Following is an attempt... (BE 20001011)
731
732         // good() returns false if any error occured, including some
733         //        formatting error.
734         // bad()  returns true if something bad happened in the buffer,
735         //        which should include file system full errors.
736
737         bool status = true;
738         if (!ofs.good()) {
739                 status = false;
740 #if 0
741                 if (ofs.bad()) {
742                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
743                 } else {
744                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
745                                << endl;
746                 }
747 #endif
748         }
749
750         return status;
751 }
752
753
754 namespace {
755
756 pair<int, string> const addDepth(int depth, int ldepth)
757 {
758         int d = depth * 2;
759         if (ldepth > depth)
760                 d += (ldepth - depth) * 2;
761         return make_pair(d, string(d, ' '));
762 }
763
764 }
765
766
767 string const Buffer::asciiParagraph(Paragraph const & par,
768                                     unsigned int linelen,
769                                     bool noparbreak) const
770 {
771         ostringstream buffer;
772         Paragraph::depth_type depth = 0;
773         int ltype = 0;
774         Paragraph::depth_type ltype_depth = 0;
775         bool ref_printed = false;
776 //      if (!par->previous()) {
777 #if 0
778         // begins or ends a deeper area ?
779         if (depth != par->params().depth()) {
780                 if (par->params().depth() > depth) {
781                         while (par->params().depth() > depth) {
782                                 ++depth;
783                         }
784                 } else {
785                         while (par->params().depth() < depth) {
786                                 --depth;
787                         }
788                 }
789         }
790 #else
791         depth = par.params().depth();
792 #endif
793
794         // First write the layout
795         string const & tmp = par.layout()->name();
796         if (compare_no_case(tmp, "itemize") == 0) {
797                 ltype = 1;
798                 ltype_depth = depth + 1;
799         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
800                 ltype = 2;
801                 ltype_depth = depth + 1;
802         } else if (contains(ascii_lowercase(tmp), "ection")) {
803                 ltype = 3;
804                 ltype_depth = depth + 1;
805         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
806                 ltype = 4;
807                 ltype_depth = depth + 1;
808         } else if (compare_ascii_no_case(tmp, "description") == 0) {
809                 ltype = 5;
810                 ltype_depth = depth + 1;
811         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
812                 ltype = 6;
813                 ltype_depth = 0;
814         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
815                 ltype = 7;
816                 ltype_depth = 0;
817         } else {
818                 ltype = 0;
819                 ltype_depth = 0;
820         }
821
822         /* maybe some vertical spaces */
823
824         /* the labelwidthstring used in lists */
825
826         /* some lines? */
827
828         /* some pagebreaks? */
829
830         /* noindent ? */
831
832         /* what about the alignment */
833
834         // linelen <= 0 is special and means we don't have paragraph breaks
835
836         string::size_type currlinelen = 0;
837
838         if (!noparbreak) {
839                 if (linelen > 0)
840                         buffer << "\n\n";
841
842                 buffer << string(depth * 2, ' ');
843                 currlinelen += depth * 2;
844
845                 //--
846                 // we should probably change to the paragraph language in the
847                 // gettext here (if possible) so that strings are outputted in
848                 // the correct language! (20012712 Jug)
849                 //--
850                 switch (ltype) {
851                 case 0: // Standard
852                 case 4: // (Sub)Paragraph
853                 case 5: // Description
854                         break;
855                 case 6: // Abstract
856                         if (linelen > 0) {
857                                 buffer << _("Abstract") << "\n\n";
858                                 currlinelen = 0;
859                         } else {
860                                 string const abst = _("Abstract: ");
861                                 buffer << abst;
862                                 currlinelen += abst.length();
863                         }
864                         break;
865                 case 7: // Bibliography
866                         if (!ref_printed) {
867                                 if (linelen > 0) {
868                                         buffer << _("References") << "\n\n";
869                                         currlinelen = 0;
870                                 } else {
871                                         string const refs = _("References: ");
872                                         buffer << refs;
873                                         currlinelen += refs.length();
874                                 }
875
876                                 ref_printed = true;
877                         }
878                         break;
879                 default:
880                 {
881                         string const parlab = par.params().labelString();
882                         buffer << parlab << ' ';
883                         currlinelen += parlab.length() + 1;
884                 }
885                 break;
886
887                 }
888         }
889
890         if (!currlinelen) {
891                 pair<int, string> p = addDepth(depth, ltype_depth);
892                 buffer << p.second;
893                 currlinelen += p.first;
894         }
895
896         // this is to change the linebreak to do it by word a bit more
897         // intelligent hopefully! (only in the case where we have a
898         // max linelength!) (Jug)
899
900         string word;
901
902         for (pos_type i = 0; i < par.size(); ++i) {
903                 char c = par.getUChar(params, i);
904                 switch (c) {
905                 case Paragraph::META_INSET:
906                 {
907                         Inset const * inset = par.getInset(i);
908                         if (inset) {
909                                 if (linelen > 0) {
910                                         buffer << word;
911                                         currlinelen += word.length();
912                                         word.erase();
913                                 }
914                                 if (inset->ascii(this, buffer, linelen)) {
915                                         // to be sure it breaks paragraph
916                                         currlinelen += linelen;
917                                 }
918                         }
919                 }
920                 break;
921
922                 default:
923                         if (c == ' ') {
924                                 if (linelen > 0 &&
925                                     currlinelen + word.length() > linelen - 10) {
926                                         buffer << "\n";
927                                         pair<int, string> p = addDepth(depth, ltype_depth);
928                                         buffer << p.second;
929                                         currlinelen = p.first;
930                                 }
931
932                                 buffer << word << ' ';
933                                 currlinelen += word.length() + 1;
934                                 word.erase();
935
936                         } else {
937                                 if (c != '\0') {
938                                         word += c;
939                                 } else {
940                                         lyxerr[Debug::INFO] <<
941                                                 "writeAsciiFile: NULL char in structure." << endl;
942                                 }
943                                 if ((linelen > 0) &&
944                                         (currlinelen + word.length()) > linelen)
945                                 {
946                                         buffer << "\n";
947
948                                         pair<int, string> p =
949                                                 addDepth(depth, ltype_depth);
950                                         buffer << p.second;
951                                         currlinelen = p.first;
952                                 }
953                         }
954                         break;
955                 }
956         }
957         buffer << word;
958         return STRCONV(buffer.str());
959 }
960
961
962 void Buffer::writeFileAscii(string const & fname, int linelen)
963 {
964         ofstream ofs(fname.c_str());
965         if (!ofs) {
966                 string const file = MakeDisplayPath(fname, 50);
967 #if USE_BOOST_FORMAT
968                 boost::format fmt(_("Could not save the document\n%1$s."));
969                 fmt % file;
970                 string text = fmt.str();
971 #else
972                 string text = _("Could not save the document\n");
973                 text += file + ".";
974 #endif
975                 Alert::error(_("Could not save document"), text);
976                 return;
977         }
978         writeFileAscii(ofs, linelen);
979 }
980
981
982 void Buffer::writeFileAscii(ostream & os, int linelen)
983 {
984         ParagraphList::iterator beg = paragraphs.begin();
985         ParagraphList::iterator end = paragraphs.end();
986         ParagraphList::iterator it = beg;
987         for (; it != end; ++it) {
988                 os << asciiParagraph(*it, linelen, it == beg);
989         }
990         os << "\n";
991 }
992
993
994
995 void Buffer::makeLaTeXFile(string const & fname,
996                            string const & original_path,
997                            bool nice, bool only_body, bool only_preamble)
998 {
999         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1000
1001         ofstream ofs(fname.c_str());
1002         if (!ofs) {
1003                 string const file = MakeDisplayPath(fname, 50);
1004 #if USE_BOOST_FORMAT
1005                 boost::format fmt(_("Could not open the specified document\n%1$s."));
1006                 fmt % file;
1007                 string text = fmt.str();
1008 #else
1009                 string text = _("Could not open the specified document\n");
1010                 text += file + ".";
1011 #endif
1012                 Alert::error(_("Could not open file"), text);
1013                 return;
1014         }
1015
1016         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1017
1018         ofs.close();
1019         if (ofs.fail()) {
1020                 lyxerr << "File was not closed properly." << endl;
1021         }
1022 }
1023
1024
1025 void Buffer::makeLaTeXFile(ostream & os,
1026                            string const & original_path,
1027                            bool nice, bool only_body, bool only_preamble)
1028 {
1029         niceFile = nice; // this will be used by Insetincludes.
1030
1031         // validate the buffer.
1032         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1033         LaTeXFeatures features(params);
1034         validate(features);
1035         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1036
1037         texrow.reset();
1038         // The starting paragraph of the coming rows is the
1039         // first paragraph of the document. (Asger)
1040         texrow.start(&*(paragraphs.begin()), 0);
1041
1042         if (!only_body && nice) {
1043                 os << "%% " << lyx_docversion << " created this file.  "
1044                         "For more info, see http://www.lyx.org/.\n"
1045                         "%% Do not edit unless you really know what "
1046                         "you are doing.\n";
1047                 texrow.newline();
1048                 texrow.newline();
1049         }
1050         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1051         // There are a few differences between nice LaTeX and usual files:
1052         // usual is \batchmode and has a
1053         // special input@path to allow the including of figures
1054         // with either \input or \includegraphics (what figinsets do).
1055         // input@path is set when the actual parameter
1056         // original_path is set. This is done for usual tex-file, but not
1057         // for nice-latex-file. (Matthias 250696)
1058         if (!only_body) {
1059                 if (!nice) {
1060                         // code for usual, NOT nice-latex-file
1061                         os << "\\batchmode\n"; // changed
1062                         // from \nonstopmode
1063                         texrow.newline();
1064                 }
1065                 if (!original_path.empty()) {
1066                         string inputpath = os::external_path(original_path);
1067                         subst(inputpath, "~", "\\string~");
1068                         os << "\\makeatletter\n"
1069                             << "\\def\\input@path{{"
1070                             << inputpath << "/}}\n"
1071                             << "\\makeatother\n";
1072                         texrow.newline();
1073                         texrow.newline();
1074                         texrow.newline();
1075                 }
1076
1077                 // Write the preamble
1078                 params.writeLaTeX(os, features, texrow);
1079
1080                 if (only_preamble)
1081                         return;
1082
1083                 // make the body.
1084                 os << "\\begin{document}\n";
1085                 texrow.newline();
1086         } // only_body
1087         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1088
1089         if (!lyxrc.language_auto_begin) {
1090                 os << subst(lyxrc.language_command_begin, "$$lang",
1091                              params.language->babel())
1092                     << endl;
1093                 texrow.newline();
1094         }
1095
1096         latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1097
1098         // add this just in case after all the paragraphs
1099         os << endl;
1100         texrow.newline();
1101
1102         if (!lyxrc.language_auto_end) {
1103                 os << subst(lyxrc.language_command_end, "$$lang",
1104                              params.language->babel())
1105                     << endl;
1106                 texrow.newline();
1107         }
1108
1109         if (!only_body) {
1110                 os << "\\end{document}\n";
1111                 texrow.newline();
1112
1113                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1114         } else {
1115                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1116                                      << endl;
1117         }
1118
1119         // Just to be sure. (Asger)
1120         texrow.newline();
1121
1122         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1123         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1124                             << '.' << endl;
1125
1126         // we want this to be true outside previews (for insetexternal)
1127         niceFile = true;
1128 }
1129
1130
1131 bool Buffer::isLatex() const
1132 {
1133         return params.getLyXTextClass().outputType() == LATEX;
1134 }
1135
1136
1137 bool Buffer::isLinuxDoc() const
1138 {
1139         return params.getLyXTextClass().outputType() == LINUXDOC;
1140 }
1141
1142
1143 bool Buffer::isLiterate() const
1144 {
1145         return params.getLyXTextClass().outputType() == LITERATE;
1146 }
1147
1148
1149 bool Buffer::isDocBook() const
1150 {
1151         return params.getLyXTextClass().outputType() == DOCBOOK;
1152 }
1153
1154
1155 bool Buffer::isSGML() const
1156 {
1157         LyXTextClass const & tclass = params.getLyXTextClass();
1158
1159         return tclass.outputType() == LINUXDOC ||
1160                tclass.outputType() == DOCBOOK;
1161 }
1162
1163
1164 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1165 {
1166         ofstream ofs(fname.c_str());
1167
1168         if (!ofs) {
1169                 string const file = MakeDisplayPath(fname, 50);
1170 #if USE_BOOST_FORMAT
1171                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1172                 fmt % file;
1173                 string text = fmt.str();
1174 #else
1175                 string text = _("Could not save the specified document\n");
1176                 text += file + _(".\n");
1177 #endif
1178                 Alert::error(_("Could not save document"), text);
1179                 return;
1180         }
1181
1182         niceFile = nice; // this will be used by included files.
1183
1184         LaTeXFeatures features(params);
1185
1186         validate(features);
1187
1188         texrow.reset();
1189
1190         LyXTextClass const & tclass = params.getLyXTextClass();
1191
1192         string top_element = tclass.latexname();
1193
1194         if (!body_only) {
1195                 ofs << "<!doctype linuxdoc system";
1196
1197                 string preamble = params.preamble;
1198                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1199                          : fname;
1200                 preamble += features.getIncludedFiles(name);
1201                 preamble += features.getLyXSGMLEntities();
1202
1203                 if (!preamble.empty()) {
1204                         ofs << " [ " << preamble << " ]";
1205                 }
1206                 ofs << ">\n\n";
1207
1208                 if (params.options.empty())
1209                         sgml::openTag(ofs, 0, false, top_element);
1210                 else {
1211                         string top = top_element;
1212                         top += ' ';
1213                         top += params.options;
1214                         sgml::openTag(ofs, 0, false, top);
1215                 }
1216         }
1217
1218         ofs << "<!-- "  << lyx_docversion
1219             << " created this file. For more info see http://www.lyx.org/"
1220             << " -->\n";
1221
1222         Paragraph::depth_type depth = 0; // paragraph depth
1223         string item_name;
1224         vector<string> environment_stack(5);
1225
1226         ParagraphList::iterator pit = paragraphs.begin();
1227         ParagraphList::iterator pend = paragraphs.end();
1228         for (; pit != pend; ++pit) {
1229                 LyXLayout_ptr const & style = pit->layout();
1230                 // treat <toc> as a special case for compatibility with old code
1231                 if (pit->isInset(0)) {
1232                         Inset * inset = pit->getInset(0);
1233                         Inset::Code lyx_code = inset->lyxCode();
1234                         if (lyx_code == Inset::TOC_CODE) {
1235                                 string const temp = "toc";
1236                                 sgml::openTag(ofs, depth, false, temp);
1237                                 continue;
1238                         }
1239                 }
1240
1241                 // environment tag closing
1242                 for (; depth > pit->params().depth(); --depth) {
1243                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1244                         environment_stack[depth].erase();
1245                 }
1246
1247                 // write opening SGML tags
1248                 switch (style->latextype) {
1249                 case LATEX_PARAGRAPH:
1250                         if (depth == pit->params().depth()
1251                            && !environment_stack[depth].empty()) {
1252                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1253                                 environment_stack[depth].erase();
1254                                 if (depth)
1255                                         --depth;
1256                                 else
1257                                         ofs << "</p>";
1258                         }
1259                         sgml::openTag(ofs, depth, false, style->latexname());
1260                         break;
1261
1262                 case LATEX_COMMAND:
1263                         if (depth != 0)
1264                                 sgmlError(&*pit, 0,
1265                                           _("Error: Wrong depth for LatexType Command.\n"));
1266
1267                         if (!environment_stack[depth].empty()) {
1268                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1269                                 ofs << "</p>";
1270                         }
1271
1272                         environment_stack[depth].erase();
1273                         sgml::openTag(ofs, depth, false, style->latexname());
1274                         break;
1275
1276                 case LATEX_ENVIRONMENT:
1277                 case LATEX_ITEM_ENVIRONMENT:
1278                 case LATEX_BIB_ENVIRONMENT:
1279                 {
1280                         string const & latexname = style->latexname();
1281
1282                         if (depth == pit->params().depth()
1283                             && environment_stack[depth] != latexname) {
1284                                 sgml::closeTag(ofs, depth, false,
1285                                              environment_stack[depth]);
1286                                 environment_stack[depth].erase();
1287                         }
1288                         if (depth < pit->params().depth()) {
1289                                depth = pit->params().depth();
1290                                environment_stack[depth].erase();
1291                         }
1292                         if (environment_stack[depth] != latexname) {
1293                                 if (depth == 0) {
1294                                         sgml::openTag(ofs, depth, false, "p");
1295                                 }
1296                                 sgml::openTag(ofs, depth, false, latexname);
1297
1298                                 if (environment_stack.size() == depth + 1)
1299                                         environment_stack.push_back("!-- --");
1300                                 environment_stack[depth] = latexname;
1301                         }
1302
1303                         if (style->latexparam() == "CDATA")
1304                                 ofs << "<![CDATA[";
1305
1306                         if (style->latextype == LATEX_ENVIRONMENT) break;
1307
1308                         if (style->labeltype == LABEL_MANUAL)
1309                                 item_name = "tag";
1310                         else
1311                                 item_name = "item";
1312
1313                         sgml::openTag(ofs, depth + 1, false, item_name);
1314                 }
1315                 break;
1316
1317                 default:
1318                         sgml::openTag(ofs, depth, false, style->latexname());
1319                         break;
1320                 }
1321
1322                 simpleLinuxDocOnePar(ofs, pit, depth);
1323
1324                 ofs << "\n";
1325                 // write closing SGML tags
1326                 switch (style->latextype) {
1327                 case LATEX_COMMAND:
1328                         break;
1329                 case LATEX_ENVIRONMENT:
1330                 case LATEX_ITEM_ENVIRONMENT:
1331                 case LATEX_BIB_ENVIRONMENT:
1332                         if (style->latexparam() == "CDATA")
1333                                 ofs << "]]>";
1334                         break;
1335                 default:
1336                         sgml::closeTag(ofs, depth, false, style->latexname());
1337                         break;
1338                 }
1339         }
1340
1341         // Close open tags
1342         for (int i = depth; i >= 0; --i)
1343                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1344
1345         if (!body_only) {
1346                 ofs << "\n\n";
1347                 sgml::closeTag(ofs, 0, false, top_element);
1348         }
1349
1350         ofs.close();
1351         // How to check for successful close
1352
1353         // we want this to be true outside previews (for insetexternal)
1354         niceFile = true;
1355 }
1356
1357
1358 // checks, if newcol chars should be put into this line
1359 // writes newline, if necessary.
1360 namespace {
1361
1362 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1363                           string::size_type newcol)
1364 {
1365         colcount += newcol;
1366         if (colcount > lyxrc.ascii_linelen) {
1367                 os << "\n";
1368                 colcount = newcol; // assume write after this call
1369         }
1370 }
1371
1372 enum PAR_TAG {
1373         NONE=0,
1374         TT = 1,
1375         SF = 2,
1376         BF = 4,
1377         IT = 8,
1378         SL = 16,
1379         EM = 32
1380 };
1381
1382
1383 string tag_name(PAR_TAG const & pt) {
1384         switch (pt) {
1385         case NONE: return "!-- --";
1386         case TT: return "tt";
1387         case SF: return "sf";
1388         case BF: return "bf";
1389         case IT: return "it";
1390         case SL: return "sl";
1391         case EM: return "em";
1392         }
1393         return "";
1394 }
1395
1396
1397 inline
1398 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1399 {
1400         p1 = static_cast<PAR_TAG>(p1 | p2);
1401 }
1402
1403
1404 inline
1405 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1406 {
1407         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1408 }
1409
1410 } // anon
1411
1412
1413 // Handle internal paragraph parsing -- layout already processed.
1414 void Buffer::simpleLinuxDocOnePar(ostream & os,
1415         ParagraphList::iterator par,
1416         Paragraph::depth_type /*depth*/) const
1417 {
1418         LyXLayout_ptr const & style = par->layout();
1419
1420         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1421
1422         // gets paragraph main font
1423         LyXFont font_old;
1424         bool desc_on;
1425         if (style->labeltype == LABEL_MANUAL) {
1426                 font_old = style->labelfont;
1427                 desc_on = true;
1428         } else {
1429                 font_old = style->font;
1430                 desc_on = false;
1431         }
1432
1433         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1434         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1435         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1436         bool is_em = false;
1437
1438         stack<PAR_TAG> tag_state;
1439         // parsing main loop
1440         for (pos_type i = 0; i < par->size(); ++i) {
1441
1442                 PAR_TAG tag_close = NONE;
1443                 list < PAR_TAG > tag_open;
1444
1445                 LyXFont const font = par->getFont(params, i, outerFont(par, paragraphs));
1446
1447                 if (font_old.family() != font.family()) {
1448                         switch (family_type) {
1449                         case LyXFont::SANS_FAMILY:
1450                                 tag_close |= SF;
1451                                 break;
1452                         case LyXFont::TYPEWRITER_FAMILY:
1453                                 tag_close |= TT;
1454                                 break;
1455                         default:
1456                                 break;
1457                         }
1458
1459                         family_type = font.family();
1460
1461                         switch (family_type) {
1462                         case LyXFont::SANS_FAMILY:
1463                                 tag_open.push_back(SF);
1464                                 break;
1465                         case LyXFont::TYPEWRITER_FAMILY:
1466                                 tag_open.push_back(TT);
1467                                 break;
1468                         default:
1469                                 break;
1470                         }
1471                 }
1472
1473                 if (font_old.series() != font.series()) {
1474                         switch (series_type) {
1475                         case LyXFont::BOLD_SERIES:
1476                                 tag_close |= BF;
1477                                 break;
1478                         default:
1479                                 break;
1480                         }
1481
1482                         series_type = font.series();
1483
1484                         switch (series_type) {
1485                         case LyXFont::BOLD_SERIES:
1486                                 tag_open.push_back(BF);
1487                                 break;
1488                         default:
1489                                 break;
1490                         }
1491
1492                 }
1493
1494                 if (font_old.shape() != font.shape()) {
1495                         switch (shape_type) {
1496                         case LyXFont::ITALIC_SHAPE:
1497                                 tag_close |= IT;
1498                                 break;
1499                         case LyXFont::SLANTED_SHAPE:
1500                                 tag_close |= SL;
1501                                 break;
1502                         default:
1503                                 break;
1504                         }
1505
1506                         shape_type = font.shape();
1507
1508                         switch (shape_type) {
1509                         case LyXFont::ITALIC_SHAPE:
1510                                 tag_open.push_back(IT);
1511                                 break;
1512                         case LyXFont::SLANTED_SHAPE:
1513                                 tag_open.push_back(SL);
1514                                 break;
1515                         default:
1516                                 break;
1517                         }
1518                 }
1519                 // handle <em> tag
1520                 if (font_old.emph() != font.emph()) {
1521                         if (font.emph() == LyXFont::ON) {
1522                                 tag_open.push_back(EM);
1523                                 is_em = true;
1524                         }
1525                         else if (is_em) {
1526                                 tag_close |= EM;
1527                                 is_em = false;
1528                         }
1529                 }
1530
1531                 list < PAR_TAG > temp;
1532                 while (!tag_state.empty() && tag_close) {
1533                         PAR_TAG k =  tag_state.top();
1534                         tag_state.pop();
1535                         os << "</" << tag_name(k) << '>';
1536                         if (tag_close & k)
1537                                 reset(tag_close,k);
1538                         else
1539                                 temp.push_back(k);
1540                 }
1541
1542                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1543                     j != temp.end(); ++j) {
1544                         tag_state.push(*j);
1545                         os << '<' << tag_name(*j) << '>';
1546                 }
1547
1548                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1549                     j != tag_open.end(); ++j) {
1550                         tag_state.push(*j);
1551                         os << '<' << tag_name(*j) << '>';
1552                 }
1553
1554                 char c = par->getChar(i);
1555
1556                 if (c == Paragraph::META_INSET) {
1557                         Inset * inset = par->getInset(i);
1558                         inset->linuxdoc(this, os);
1559                         font_old = font;
1560                         continue;
1561                 }
1562
1563                 if (style->latexparam() == "CDATA") {
1564                         // "TeX"-Mode on == > SGML-Mode on.
1565                         if (c != '\0')
1566                                 os << c;
1567                         ++char_line_count;
1568                 } else {
1569                         bool ws;
1570                         string str;
1571                         boost::tie(ws, str) = sgml::escapeChar(c);
1572                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
1573                                 // in freespacing mode, spaces are
1574                                 // non-breaking characters
1575                                 if (desc_on) {// if char is ' ' then...
1576
1577                                         ++char_line_count;
1578                                         sgmlLineBreak(os, char_line_count, 6);
1579                                         os << "</tag>";
1580                                         desc_on = false;
1581                                 } else  {
1582                                         sgmlLineBreak(os, char_line_count, 1);
1583                                         os << c;
1584                                 }
1585                         } else {
1586                                 os << str;
1587                                 char_line_count += str.length();
1588                         }
1589                 }
1590                 font_old = font;
1591         }
1592
1593         while (!tag_state.empty()) {
1594                 os << "</" << tag_name(tag_state.top()) << '>';
1595                 tag_state.pop();
1596         }
1597
1598         // resets description flag correctly
1599         if (desc_on) {
1600                 // <tag> not closed...
1601                 sgmlLineBreak(os, char_line_count, 6);
1602                 os << "</tag>";
1603         }
1604 }
1605
1606
1607 // Print an error message.
1608 void Buffer::sgmlError(ParagraphList::iterator /*par*/, int /*pos*/,
1609         string const & /*message*/) const
1610 {
1611 #ifdef WITH_WARNINGS
1612 #warning This is wrong we cannot insert an inset like this!!!
1613         // I guess this was Jose' so I explain you more or less why this
1614         // is wrong. This way you insert something in the paragraph and
1615         // don't tell it to LyXText (row rebreaking and undo handling!!!)
1616         // I deactivate this code, have a look at BufferView::insertErrors
1617         // how you should do this correctly! (Jug 20020315)
1618 #endif
1619 #if 0
1620         // insert an error marker in text
1621         InsetError * new_inset = new InsetError(message);
1622         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1623                          params.language));
1624 #endif
1625 }
1626
1627
1628 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1629 {
1630         ofstream ofs(fname.c_str());
1631         if (!ofs) {
1632                 string const file = MakeDisplayPath(fname, 50);
1633 #if USE_BOOST_FORMAT
1634                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1635                 fmt % file;
1636                 string text = fmt.str();
1637 #else
1638                 string text = _("Could not save the specified document\n");
1639                 text += file + _(".\n");
1640 #endif
1641                 Alert::error(_("Could not save document"), text);
1642                 return;
1643         }
1644
1645         niceFile = nice; // this will be used by Insetincludes.
1646
1647         LaTeXFeatures features(params);
1648         validate(features);
1649
1650         texrow.reset();
1651
1652         LyXTextClass const & tclass = params.getLyXTextClass();
1653         string top_element = tclass.latexname();
1654
1655         if (!only_body) {
1656                 ofs << "<!DOCTYPE " << top_element
1657                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1658
1659                 string preamble = params.preamble;
1660                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1661                          : fname;
1662                 preamble += features.getIncludedFiles(name);
1663                 preamble += features.getLyXSGMLEntities();
1664
1665                 if (!preamble.empty()) {
1666                         ofs << "\n [ " << preamble << " ]";
1667                 }
1668                 ofs << ">\n\n";
1669         }
1670
1671         string top = top_element;
1672         top += " lang=\"";
1673         top += params.language->code();
1674         top += '"';
1675
1676         if (!params.options.empty()) {
1677                 top += ' ';
1678                 top += params.options;
1679         }
1680         sgml::openTag(ofs, 0, false, top);
1681
1682         ofs << "<!-- DocBook file was created by " << lyx_docversion
1683             << "\n  See http://www.lyx.org/ for more information -->\n";
1684
1685         vector<string> environment_stack(10);
1686         vector<string> environment_inner(10);
1687         vector<string> command_stack(10);
1688
1689         bool command_flag = false;
1690         Paragraph::depth_type command_depth = 0;
1691         Paragraph::depth_type command_base = 0;
1692         Paragraph::depth_type cmd_depth = 0;
1693         Paragraph::depth_type depth = 0; // paragraph depth
1694
1695         string item_name;
1696         string command_name;
1697
1698         ParagraphList::iterator par = paragraphs.begin();
1699         ParagraphList::iterator pend = paragraphs.end();
1700
1701         for (; par != pend; ++par) {
1702                 string sgmlparam;
1703                 string c_depth;
1704                 string c_params;
1705                 int desc_on = 0; // description mode
1706
1707                 LyXLayout_ptr const & style = par->layout();
1708
1709                 // environment tag closing
1710                 for (; depth > par->params().depth(); --depth) {
1711                         if (environment_inner[depth] != "!-- --") {
1712                                 item_name = "listitem";
1713                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1714                                 if (environment_inner[depth] == "varlistentry")
1715                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1716                         }
1717                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1718                         environment_stack[depth].erase();
1719                         environment_inner[depth].erase();
1720                 }
1721
1722                 if (depth == par->params().depth()
1723                    && environment_stack[depth] != style->latexname()
1724                    && !environment_stack[depth].empty()) {
1725                         if (environment_inner[depth] != "!-- --") {
1726                                 item_name= "listitem";
1727                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1728                                 if (environment_inner[depth] == "varlistentry")
1729                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1730                         }
1731
1732                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1733
1734                         environment_stack[depth].erase();
1735                         environment_inner[depth].erase();
1736                 }
1737
1738                 // Write opening SGML tags.
1739                 switch (style->latextype) {
1740                 case LATEX_PARAGRAPH:
1741                         sgml::openTag(ofs, depth + command_depth,
1742                                     false, style->latexname());
1743                         break;
1744
1745                 case LATEX_COMMAND:
1746                         if (depth != 0)
1747                                 sgmlError(par, 0,
1748                                           _("Error: Wrong depth for LatexType Command.\n"));
1749
1750                         command_name = style->latexname();
1751
1752                         sgmlparam = style->latexparam();
1753                         c_params = split(sgmlparam, c_depth,'|');
1754
1755                         cmd_depth = lyx::atoi(c_depth);
1756
1757                         if (command_flag) {
1758                                 if (cmd_depth < command_base) {
1759                                         for (Paragraph::depth_type j = command_depth;
1760                                              j >= command_base; --j) {
1761                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1762                                                 ofs << endl;
1763                                         }
1764                                         command_depth = command_base = cmd_depth;
1765                                 } else if (cmd_depth <= command_depth) {
1766                                         for (int j = command_depth;
1767                                              j >= int(cmd_depth); --j) {
1768                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1769                                                 ofs << endl;
1770                                         }
1771                                         command_depth = cmd_depth;
1772                                 } else
1773                                         command_depth = cmd_depth;
1774                         } else {
1775                                 command_depth = command_base = cmd_depth;
1776                                 command_flag = true;
1777                         }
1778                         if (command_stack.size() == command_depth + 1)
1779                                 command_stack.push_back(string());
1780                         command_stack[command_depth] = command_name;
1781
1782                         // treat label as a special case for
1783                         // more WYSIWYM handling.
1784                         // This is a hack while paragraphs can't have
1785                         // attributes, like id in this case.
1786                         if (par->isInset(0)) {
1787                                 Inset * inset = par->getInset(0);
1788                                 Inset::Code lyx_code = inset->lyxCode();
1789                                 if (lyx_code == Inset::LABEL_CODE) {
1790                                         command_name += " id=\"";
1791                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1792                                         command_name += '"';
1793                                         desc_on = 3;
1794                                 }
1795                         }
1796
1797                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1798
1799                         item_name = c_params.empty() ? "title" : c_params;
1800                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1801                         break;
1802
1803                 case LATEX_ENVIRONMENT:
1804                 case LATEX_ITEM_ENVIRONMENT:
1805                         if (depth < par->params().depth()) {
1806                                 depth = par->params().depth();
1807                                 environment_stack[depth].erase();
1808                         }
1809
1810                         if (environment_stack[depth] != style->latexname()) {
1811                                 if (environment_stack.size() == depth + 1) {
1812                                         environment_stack.push_back("!-- --");
1813                                         environment_inner.push_back("!-- --");
1814                                 }
1815                                 environment_stack[depth] = style->latexname();
1816                                 environment_inner[depth] = "!-- --";
1817                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1818                         } else {
1819                                 if (environment_inner[depth] != "!-- --") {
1820                                         item_name= "listitem";
1821                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1822                                         if (environment_inner[depth] == "varlistentry")
1823                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1824                                 }
1825                         }
1826
1827                         if (style->latextype == LATEX_ENVIRONMENT) {
1828                                 if (!style->latexparam().empty()) {
1829                                         if (style->latexparam() == "CDATA")
1830                                                 ofs << "<![CDATA[";
1831                                         else
1832                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1833                                 }
1834                                 break;
1835                         }
1836
1837                         desc_on = (style->labeltype == LABEL_MANUAL);
1838
1839                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1840                         sgml::openTag(ofs, depth + 1 + command_depth,
1841                                     false, environment_inner[depth]);
1842
1843                         item_name = desc_on ? "term" : "para";
1844                         sgml::openTag(ofs, depth + 1 + command_depth,
1845                                     false, item_name);
1846                         break;
1847                 default:
1848                         sgml::openTag(ofs, depth + command_depth,
1849                                     false, style->latexname());
1850                         break;
1851                 }
1852
1853                 simpleDocBookOnePar(ofs, par, desc_on,
1854                                     depth + 1 + command_depth);
1855
1856                 string end_tag;
1857                 // write closing SGML tags
1858                 switch (style->latextype) {
1859                 case LATEX_COMMAND:
1860                         end_tag = c_params.empty() ? "title" : c_params;
1861                         sgml::closeTag(ofs, depth + command_depth,
1862                                      false, end_tag);
1863                         break;
1864                 case LATEX_ENVIRONMENT:
1865                         if (!style->latexparam().empty()) {
1866                                 if (style->latexparam() == "CDATA")
1867                                         ofs << "]]>";
1868                                 else
1869                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1870                         }
1871                         break;
1872                 case LATEX_ITEM_ENVIRONMENT:
1873                         if (desc_on == 1) break;
1874                         end_tag = "para";
1875                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1876                         break;
1877                 case LATEX_PARAGRAPH:
1878                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1879                         break;
1880                 default:
1881                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1882                         break;
1883                 }
1884         }
1885
1886         // Close open tags
1887         for (int d = depth; d >= 0; --d) {
1888                 if (!environment_stack[depth].empty()) {
1889                         if (environment_inner[depth] != "!-- --") {
1890                                 item_name = "listitem";
1891                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1892                                if (environment_inner[depth] == "varlistentry")
1893                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1894                         }
1895
1896                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1897                 }
1898         }
1899
1900         for (int j = command_depth; j >= 0 ; --j)
1901                 if (!command_stack[j].empty()) {
1902                         sgml::closeTag(ofs, j, false, command_stack[j]);
1903                         ofs << endl;
1904                 }
1905
1906         ofs << "\n\n";
1907         sgml::closeTag(ofs, 0, false, top_element);
1908
1909         ofs.close();
1910         // How to check for successful close
1911
1912         // we want this to be true outside previews (for insetexternal)
1913         niceFile = true;
1914 }
1915
1916
1917 void Buffer::simpleDocBookOnePar(ostream & os,
1918                                  ParagraphList::iterator par, int & desc_on,
1919                                  Paragraph::depth_type depth) const
1920 {
1921         bool emph_flag = false;
1922
1923         LyXLayout_ptr const & style = par->layout();
1924
1925         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1926
1927         int char_line_count = depth;
1928         //if (!style.free_spacing)
1929         //      os << string(depth,' ');
1930
1931         // parsing main loop
1932         for (pos_type i = 0; i < par->size(); ++i) {
1933                 LyXFont font = par->getFont(params, i, outerFont(par, paragraphs));
1934
1935                 // handle <emphasis> tag
1936                 if (font_old.emph() != font.emph()) {
1937                         if (font.emph() == LyXFont::ON) {
1938                                 if (style->latexparam() == "CDATA")
1939                                         os << "]]>";
1940                                 os << "<emphasis>";
1941                                 if (style->latexparam() == "CDATA")
1942                                         os << "<![CDATA[";
1943                                 emph_flag = true;
1944                         } else if (i) {
1945                                 if (style->latexparam() == "CDATA")
1946                                         os << "]]>";
1947                                 os << "</emphasis>";
1948                                 if (style->latexparam() == "CDATA")
1949                                         os << "<![CDATA[";
1950                                 emph_flag = false;
1951                         }
1952                 }
1953
1954
1955                 if (par->isInset(i)) {
1956                         Inset * inset = par->getInset(i);
1957                         // don't print the inset in position 0 if desc_on == 3 (label)
1958                         if (i || desc_on != 3) {
1959                                 if (style->latexparam() == "CDATA")
1960                                         os << "]]>";
1961                                 inset->docbook(this, os, false);
1962                                 if (style->latexparam() == "CDATA")
1963                                         os << "<![CDATA[";
1964                         }
1965                 } else {
1966                         char c = par->getChar(i);
1967                         bool ws;
1968                         string str;
1969                         boost::tie(ws, str) = sgml::escapeChar(c);
1970
1971                         if (style->pass_thru) {
1972                                 os << c;
1973                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
1974                                         os << str;
1975                         } else if (desc_on ==1) {
1976                                 ++char_line_count;
1977                                 os << "\n</term><listitem><para>";
1978                                 desc_on = 2;
1979                         } else {
1980                                 os << ' ';
1981                         }
1982                 }
1983                 font_old = font;
1984         }
1985
1986         if (emph_flag) {
1987                 if (style->latexparam() == "CDATA")
1988                         os << "]]>";
1989                 os << "</emphasis>";
1990                 if (style->latexparam() == "CDATA")
1991                         os << "<![CDATA[";
1992         }
1993
1994         // resets description flag correctly
1995         if (desc_on == 1) {
1996                 // <term> not closed...
1997                 os << "</term>\n<listitem><para>&nbsp;</para>";
1998         }
1999         if (style->free_spacing)
2000                 os << '\n';
2001 }
2002
2003
2004 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2005 // Other flags: -wall -v0 -x
2006 int Buffer::runChktex()
2007 {
2008         if (!users->text) return 0;
2009
2010         users->owner()->busy(true);
2011
2012         // get LaTeX-Filename
2013         string const name = getLatexName();
2014         string path = filePath();
2015
2016         string const org_path = path;
2017         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2018                 path = tmppath;
2019         }
2020
2021         Path p(path); // path to LaTeX file
2022         users->owner()->message(_("Running chktex..."));
2023
2024         // Remove all error insets
2025         bool const removedErrorInsets = users->removeAutoInsets();
2026
2027         // Generate the LaTeX file if neccessary
2028         makeLaTeXFile(name, org_path, false);
2029
2030         TeXErrors terr;
2031         Chktex chktex(lyxrc.chktex_command, name, filePath());
2032         int res = chktex.run(terr); // run chktex
2033
2034         if (res == -1) {
2035                 Alert::error(_("chktex failure"),
2036                         _("Could not run chktex successfully."));
2037         } else if (res > 0) {
2038                 // Insert all errors as errors boxes
2039                 users->insertErrors(terr);
2040         }
2041
2042         // if we removed error insets before we ran chktex or if we inserted
2043         // error insets after we ran chktex, this must be run:
2044         if (removedErrorInsets || res) {
2045 #warning repaint needed here, or do you mean update() ?
2046                 users->repaint();
2047                 users->fitCursor();
2048         }
2049         users->owner()->busy(false);
2050
2051         return res;
2052 }
2053
2054
2055 void Buffer::validate(LaTeXFeatures & features) const
2056 {
2057         LyXTextClass const & tclass = params.getLyXTextClass();
2058
2059         if (params.tracking_changes) {
2060                 features.require("dvipost");
2061                 features.require("color");
2062         }
2063
2064         // AMS Style is at document level
2065         if (params.use_amsmath == BufferParams::AMS_ON
2066             || tclass.provides(LyXTextClass::amsmath))
2067                 features.require("amsmath");
2068
2069         for_each(paragraphs.begin(), paragraphs.end(),
2070                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2071
2072         // the bullet shapes are buffer level not paragraph level
2073         // so they are tested here
2074         for (int i = 0; i < 4; ++i) {
2075                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2076                         int const font = params.user_defined_bullets[i].getFont();
2077                         if (font == 0) {
2078                                 int const c = params
2079                                         .user_defined_bullets[i]
2080                                         .getCharacter();
2081                                 if (c == 16
2082                                    || c == 17
2083                                    || c == 25
2084                                    || c == 26
2085                                    || c == 31) {
2086                                         features.require("latexsym");
2087                                 }
2088                         } else if (font == 1) {
2089                                 features.require("amssymb");
2090                         } else if ((font >= 2 && font <= 5)) {
2091                                 features.require("pifont");
2092                         }
2093                 }
2094         }
2095
2096         if (lyxerr.debugging(Debug::LATEX)) {
2097                 features.showStruct();
2098         }
2099 }
2100
2101
2102 vector<string> const Buffer::getLabelList() const
2103 {
2104         /// if this is a child document and the parent is already loaded
2105         /// Use the parent's list instead  [ale990407]
2106         if (!params.parentname.empty()
2107             && bufferlist.exists(params.parentname)) {
2108                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2109                 if (tmp)
2110                         return tmp->getLabelList();
2111         }
2112
2113         vector<string> label_list;
2114         for (inset_iterator it = inset_const_iterator_begin();
2115              it != inset_const_iterator_end(); ++it) {
2116                 vector<string> const l = it->getLabelList();
2117                 label_list.insert(label_list.end(), l.begin(), l.end());
2118         }
2119         return label_list;
2120 }
2121
2122
2123 // This is also a buffer property (ale)
2124 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2125 {
2126         /// if this is a child document and the parent is already loaded
2127         /// use the parent's list instead  [ale990412]
2128         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2129                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2130                 if (tmp) {
2131                         tmp->fillWithBibKeys(keys);
2132                         return;
2133                 }
2134         }
2135
2136         for (inset_iterator it = inset_const_iterator_begin();
2137                 it != inset_const_iterator_end(); ++it) {
2138                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2139                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2140                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2141                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2142                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2143                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2144                         string const key = bib.getContents();
2145                         string const opt = bib.getOptions();
2146                         string const ref; // = pit->asString(this, false);
2147                         string const info = opt + "TheBibliographyRef" + ref;
2148                         keys.push_back(pair<string, string>(key, info));
2149                 }
2150         }
2151 }
2152
2153
2154 bool Buffer::isDepClean(string const & name) const
2155 {
2156         DepClean::const_iterator it = dep_clean_.find(name);
2157         if (it == dep_clean_.end())
2158                 return true;
2159         return it->second;
2160 }
2161
2162
2163 void Buffer::markDepClean(string const & name)
2164 {
2165         dep_clean_[name] = true;
2166 }
2167
2168
2169 bool Buffer::dispatch(string const & command, bool * result)
2170 {
2171         // Split command string into command and argument
2172         string cmd;
2173         string line = ltrim(command);
2174         string const arg = trim(split(line, cmd, ' '));
2175
2176         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2177 }
2178
2179
2180 bool Buffer::dispatch(int action, string const & argument, bool * result)
2181 {
2182         bool dispatched = true;
2183
2184         switch (action) {
2185                 case LFUN_EXPORT: {
2186                         bool const tmp = Exporter::Export(this, argument, false);
2187                         if (result)
2188                                 *result = tmp;
2189                         break;
2190                 }
2191
2192                 default:
2193                         dispatched = false;
2194         }
2195         return dispatched;
2196 }
2197
2198
2199 void Buffer::resizeInsets(BufferView * bv)
2200 {
2201         /// then remove all LyXText in text-insets
2202         for_each(paragraphs.begin(), paragraphs.end(),
2203                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2204 }
2205
2206
2207 void Buffer::redraw()
2208 {
2209 #warning repaint needed here, or do you mean update() ?
2210         users->repaint();
2211         users->fitCursor();
2212 }
2213
2214
2215 void Buffer::changeLanguage(Language const * from, Language const * to)
2216 {
2217         lyxerr << "Changing Language!" << endl;
2218
2219         // Take care of l10n/i18n
2220         updateDocLang(to);
2221
2222         ParIterator end = par_iterator_end();
2223         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2224                 (*it)->changeLanguage(params, from, to);
2225 }
2226
2227
2228 void Buffer::updateDocLang(Language const * nlang)
2229 {
2230         messages_.reset(new Messages(nlang->code()));
2231 }
2232
2233
2234 bool Buffer::isMultiLingual()
2235 {
2236         ParIterator end = par_iterator_end();
2237         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2238                 if ((*it)->isMultiLingual(params))
2239                         return true;
2240
2241         return false;
2242 }
2243
2244
2245 void Buffer::inset_iterator::setParagraph()
2246 {
2247         while (pit != pend) {
2248                 it = pit->insetlist.begin();
2249                 if (it != pit->insetlist.end())
2250                         return;
2251                 ++pit;
2252         }
2253 }
2254
2255
2256 Inset * Buffer::getInsetFromID(int id_arg) const
2257 {
2258         for (inset_iterator it = inset_const_iterator_begin();
2259                  it != inset_const_iterator_end(); ++it)
2260         {
2261                 if (it->id() == id_arg)
2262                         return &(*it);
2263                 Inset * in = it->getInsetFromID(id_arg);
2264                 if (in)
2265                         return in;
2266         }
2267         return 0;
2268 }
2269
2270
2271 ParagraphList::iterator Buffer::getParFromID(int id) const
2272 {
2273 #warning FIXME: const correctness! (Andre)
2274         ParIterator it(const_cast<Buffer*>(this)->par_iterator_begin());
2275         ParIterator end(const_cast<Buffer*>(this)->par_iterator_end());
2276
2277 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
2278         if (id < 0) {
2279                 // John says this is called with id == -1 from undo
2280                 lyxerr << "getParFromID(), id: " << id << endl;
2281                 return 0;
2282         }
2283
2284         for (; it != end; ++it) {
2285                 // go on then, show me how to remove
2286                 // the cast
2287                 if ((*it)->id() == id) {
2288                         return *it;
2289                 }
2290         }
2291
2292         return 0;
2293 }
2294
2295
2296 ParIterator Buffer::par_iterator_begin()
2297 {
2298         return ParIterator(&*(paragraphs.begin()));
2299 }
2300
2301
2302 ParIterator Buffer::par_iterator_end()
2303 {
2304         return ParIterator();
2305 }
2306
2307 ParConstIterator Buffer::par_iterator_begin() const
2308 {
2309         return ParConstIterator(&*(paragraphs.begin()));
2310 }
2311
2312
2313 ParConstIterator Buffer::par_iterator_end() const
2314 {
2315         return ParConstIterator();
2316 }
2317
2318
2319
2320 void Buffer::addUser(BufferView * u)
2321 {
2322         users = u;
2323 }
2324
2325
2326 void Buffer::delUser(BufferView *)
2327 {
2328         users = 0;
2329 }
2330
2331
2332 Language const * Buffer::getLanguage() const
2333 {
2334         return params.language;
2335 }
2336
2337
2338 string const Buffer::B_(string const & l10n) const
2339 {
2340         if (messages_.get()) {
2341                 return messages_->get(l10n);
2342         }
2343
2344         return _(l10n);
2345 }
2346
2347
2348 bool Buffer::isClean() const
2349 {
2350         return lyx_clean;
2351 }
2352
2353
2354 bool Buffer::isBakClean() const
2355 {
2356         return bak_clean;
2357 }
2358
2359
2360 void Buffer::markClean() const
2361 {
2362         if (!lyx_clean) {
2363                 lyx_clean = true;
2364                 updateTitles();
2365         }
2366         // if the .lyx file has been saved, we don't need an
2367         // autosave
2368         bak_clean = true;
2369 }
2370
2371
2372 void Buffer::markBakClean()
2373 {
2374         bak_clean = true;
2375 }
2376
2377
2378 void Buffer::setUnnamed(bool flag)
2379 {
2380         unnamed = flag;
2381 }
2382
2383
2384 bool Buffer::isUnnamed()
2385 {
2386         return unnamed;
2387 }
2388
2389
2390 void Buffer::markDirty()
2391 {
2392         if (lyx_clean) {
2393                 lyx_clean = false;
2394                 updateTitles();
2395         }
2396         bak_clean = false;
2397
2398         DepClean::iterator it = dep_clean_.begin();
2399         DepClean::const_iterator const end = dep_clean_.end();
2400
2401         for (; it != end; ++it) {
2402                 it->second = false;
2403         }
2404 }
2405
2406
2407 string const & Buffer::fileName() const
2408 {
2409         return filename_;
2410 }
2411
2412
2413 string const & Buffer::filePath() const
2414 {
2415         return filepath_;
2416 }
2417
2418
2419 bool Buffer::isReadonly() const
2420 {
2421         return read_only;
2422 }
2423
2424
2425 BufferView * Buffer::getUser() const
2426 {
2427         return users;
2428 }
2429
2430
2431 void Buffer::setParentName(string const & name)
2432 {
2433         params.parentname = name;
2434 }
2435
2436
2437 Buffer::inset_iterator::inset_iterator()
2438         : pit(0), pend(0)
2439 {}
2440
2441
2442 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2443         : pit(p), pend(e)
2444 {
2445         setParagraph();
2446 }
2447
2448
2449 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2450 {
2451         if (pit != pend) {
2452                 ++it;
2453                 if (it == pit->insetlist.end()) {
2454                         ++pit;
2455                         setParagraph();
2456                 }
2457         }
2458         return *this;
2459 }
2460
2461
2462 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2463 {
2464         inset_iterator tmp = *this;
2465         ++*this;
2466         return tmp;
2467 }
2468
2469
2470 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2471 {
2472         return *it.getInset();
2473 }
2474
2475
2476 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2477 {
2478         return it.getInset();
2479 }
2480
2481
2482 ParagraphList::iterator Buffer::inset_iterator::getPar() const
2483 {
2484         return pit;
2485 }
2486
2487
2488 lyx::pos_type Buffer::inset_iterator::getPos() const
2489 {
2490         return it.getPos();
2491 }
2492
2493
2494 bool operator==(Buffer::inset_iterator const & iter1,
2495                 Buffer::inset_iterator const & iter2)
2496 {
2497         return iter1.pit == iter2.pit
2498                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2499 }
2500
2501
2502 bool operator!=(Buffer::inset_iterator const & iter1,
2503                 Buffer::inset_iterator const & iter2)
2504 {
2505         return !(iter1 == iter2);
2506 }