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