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