]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
rev 19644: I forgot this.
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "Biblio_typedefs.h"
16 #include "DocIterator.h"
17
18 #include "support/FileName.h"
19 #include "support/limited_stack.h"
20 #include "support/types.h"
21 #include "support/docstring.h"
22 #include "support/docstream.h"
23
24 #include <boost/scoped_ptr.hpp>
25 #include <boost/signal.hpp>
26
27 #include <iosfwd>
28 #include <string>
29 #include <map>
30 #include <utility>
31 #include <vector>
32
33
34 namespace lyx {
35
36 class BufferParams;
37 class ErrorItem;
38 class ErrorList;
39 class FuncRequest;
40 class Inset;
41 class InsetText;
42 class Font;
43 class Lexer;
44 class LyXRC;
45 class Text;
46 class LyXVC;
47 class LaTeXFeatures;
48 class Language;
49 class MacroData;
50 class OutputParams;
51 class ParConstIterator;
52 class ParIterator;
53 class ParagraphList;
54 class StableDocIterator;
55 class TeXErrors;
56 class TexRow;
57 class TocBackend;
58 class Undo;
59
60
61 /** The buffer object.
62  * This is the buffer object. It contains all the informations about
63  * a document loaded into LyX.
64  * The buffer object owns the Text (wrapped in an InsetText), which
65  * contains the individual paragraphs of the document.
66  *
67  *
68  * I am not sure if the class is complete or
69  * minimal, probably not.
70  * \author Lars Gullik Bjønnes
71   */
72 class Buffer {
73 public:
74         /// What type of log will \c getLogName() return?
75         enum LogType {
76                 latexlog, ///< LaTeX log
77                 buildlog  ///< Literate build log
78         };
79
80         /// Result of \c readFile()
81         enum ReadStatus {
82                 failure, ///< The file could not be read
83                 success, ///< The file could not be read
84                 wrongversion ///< The version of the file does not match ours
85         };
86
87         /// Method to check if a file is externally modified, used by 
88         /// isExternallyModified()
89         /**
90          * timestamp is fast but inaccurate. For example, the granularity
91          * of timestamp on a FAT filesystem is 2 second. Also, various operations
92          * may touch the timestamp of a file even when its content is unchanged.
93          *
94          * checksum is accurate but slow, which can be a problem when it is 
95          * frequently used, or used for a large file on a slow (network) file
96          * system.
97          */
98         enum CheckMethod {
99                 checksum_method,  ///< Use file check sum
100                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
101         };
102         
103         /** Constructor
104             \param file
105             \param b  optional \c false by default
106         */
107         explicit Buffer(std::string const & file, bool b = false);
108
109         /// Destructor
110         ~Buffer();
111
112         /** High-level interface to buffer functionality.
113             This function parses a command string and executes it
114         */
115         bool dispatch(std::string const & command, bool * result = 0);
116
117         /// Maybe we know the function already by number...
118         bool dispatch(FuncRequest const & func, bool * result = 0);
119
120         /// Load the autosaved file.
121         void loadAutoSaveFile();
122
123         /// read a new document from a string
124         bool readString(std::string const &);
125         /// load a new file
126         bool readFile(support::FileName const & filename);
127
128         /// read the header, returns number of unknown tokens
129         int readHeader(Lexer & lex);
130
131         /** Reads a file without header.
132             \param par if != 0 insert the file.
133             \return \c false if file is not completely read.
134         */
135         bool readDocument(Lexer &);
136
137         ///
138         void insertStringAsLines(ParagraphList & plist,
139                 pit_type &, pos_type &,
140                 Font const &, docstring const &, bool);
141         ///
142         ParIterator getParFromID(int id) const;
143         /// do we have a paragraph with this id?
144         bool hasParWithID(int id) const;
145
146         /// This signal is emitted when the buffer is changed.
147         boost::signal<void()> changed;
148         /// This signal is emitted when the buffer structure is changed.
149         boost::signal<void()> structureChanged;
150         /// This signal is emitted when some parsing error shows up.
151         boost::signal<void(std::string)> errors;
152         /// This signal is emitted when some message shows up.
153         boost::signal<void(docstring)> message;
154         /// This signal is emitted when the buffer busy status change.
155         boost::signal<void(bool)> busy;
156         /// This signal is emitted when the buffer readonly status change.
157         boost::signal<void(bool)> readonly;
158         /// Update window titles of all users.
159         boost::signal<void()> updateTitles;
160         /// Reset autosave timers for all users.
161         boost::signal<void()> resetAutosaveTimers;
162         /// This signal is emitting if the buffer is being closed.
163         boost::signal<void()> closing;
164
165
166         /** Save file.
167             Takes care of auto-save files and backup file if requested.
168             Returns \c true if the save is successful, \c false otherwise.
169         */
170         bool save() const;
171
172         /// Write document to stream. Returns \c false if unsuccesful.
173         bool write(std::ostream &) const;
174         /// Write file. Returns \c false if unsuccesful.
175         bool writeFile(support::FileName const &) const;
176
177         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
178         bool makeLaTeXFile(support::FileName const & filename,
179                            std::string const & original_path,
180                            OutputParams const &,
181                            bool output_preamble = true,
182                            bool output_body = true);
183         /** Export the buffer to LaTeX.
184             If \p os is a file stream, and params().inputenc is "auto" or
185             "default", and the buffer contains text in different languages
186             with more than one encoding, then this method will change the
187             encoding associated to \p os. Therefore you must not call this
188             method with a string stream if the output is supposed to go to a
189             file. \code
190             odocfstream ofs;
191             ofs.open("test.tex");
192             writeLaTeXSource(ofs, ...);
193             ofs.close();
194             \endcode is NOT equivalent to \code
195             odocstringstream oss;
196             writeLaTeXSource(oss, ...);
197             odocfstream ofs;
198             ofs.open("test.tex");
199             ofs << oss.str();
200             ofs.close();
201             \endcode
202          */
203         void writeLaTeXSource(odocstream & os,
204                            std::string const & original_path,
205                            OutputParams const &,
206                            bool output_preamble = true,
207                            bool output_body = true);
208         ///
209         void makeDocBookFile(support::FileName const & filename,
210                              OutputParams const & runparams_in,
211                              bool only_body = false);
212         ///
213         void writeDocBookSource(odocstream & os, std::string const & filename,
214                              OutputParams const & runparams_in,
215                              bool only_body = false);
216         /// returns the main language for the buffer (document)
217         Language const * getLanguage() const;
218         /// get l10n translated to the buffers language
219         docstring const B_(std::string const & l10n) const;
220
221         ///
222         int runChktex();
223         /// return true if the main lyx file does not need saving
224         bool isClean() const;
225         ///
226         bool isBakClean() const;
227         ///
228         bool isDepClean(std::string const & name) const;
229
230         /// whether or not disk file has been externally modified
231         bool isExternallyModified(CheckMethod method) const;
232
233         /// mark the main lyx file as not needing saving
234         void markClean() const;
235
236         ///
237         void markBakClean();
238
239         ///
240         void markDepClean(std::string const & name);
241
242         ///
243         void setUnnamed(bool flag = true);
244
245         ///
246         bool isUnnamed() const;
247
248         /// Mark this buffer as dirty.
249         void markDirty();
250
251         /// Returns the buffer's filename. It is always an absolute path.
252         std::string const fileName() const;
253
254         /// Returns the the path where the buffer lives.
255         /// It is always an absolute path.
256         std::string const & filePath() const;
257
258         /** A transformed version of the file name, adequate for LaTeX.
259             \param no_path optional if \c true then the path is stripped.
260         */
261         std::string const getLatexName(bool no_path = true) const;
262
263         /// Get thee name and type of the log.
264         std::pair<LogType, std::string> const getLogName() const;
265
266         /// Change name of buffer. Updates "read-only" flag.
267         void setFileName(std::string const & newfile);
268
269         /// Name of the document's parent
270         void setParentName(std::string const &);
271
272         /** Get the document's master (or \c this if this is not a
273             child document)
274          */
275         Buffer const * getMasterBuffer() const;
276         /** Get the document's master (or \c this if this is not a
277             child document)
278          */
279         Buffer * getMasterBuffer();
280
281         /// Is buffer read-only?
282         bool isReadonly() const;
283
284         /// Set buffer read-only flag
285         void setReadonly(bool flag = true);
286
287         /// returns \c true if the buffer contains a LaTeX document
288         bool isLatex() const;
289         /// returns \c true if the buffer contains a DocBook document
290         bool isDocBook() const;
291         /// returns \c true if the buffer contains a Wed document
292         bool isLiterate() const;
293
294         /** Validate a buffer for LaTeX.
295             This validates the buffer, and returns a struct for use by
296             #makeLaTeX# and others. Its main use is to figure out what
297             commands and packages need to be included in the LaTeX file.
298             It (should) also check that the needed constructs are there
299             (i.e. that the \refs points to coresponding \labels). It
300             should perhaps inset "error" insets to help the user correct
301             obvious mistakes.
302         */
303         void validate(LaTeXFeatures &) const;
304
305         /// return all bibkeys from buffer and its childs
306         void fillWithBibKeys(biblio::BibKeyList & keys) const;
307         /// Update the cache with all bibfiles in use (including bibfiles
308         /// of loaded child documents).
309         void updateBibfilesCache();
310         /// Return the cache with all bibfiles in use (including bibfiles
311         /// of loaded child documents).
312         std::vector<support::FileName> const & getBibfilesCache() const;
313         ///
314         void getLabelList(std::vector<docstring> &) const;
315
316         ///
317         void changeLanguage(Language const * from, Language const * to);
318
319         ///
320         bool isMultiLingual() const;
321
322         /// Does this mean that this is buffer local?
323         limited_stack<Undo> & undostack();
324         limited_stack<Undo> const & undostack() const;
325
326         /// Does this mean that this is buffer local?
327         limited_stack<Undo> & redostack();
328         limited_stack<Undo> const & redostack() const;
329
330         ///
331         BufferParams & params();
332         BufferParams const & params() const;
333
334         /** The list of paragraphs.
335             This is a linked list of paragraph, this list holds the
336             whole contents of the document.
337          */
338         ParagraphList & paragraphs();
339         ParagraphList const & paragraphs() const;
340
341         /// LyX version control object.
342         LyXVC & lyxvc();
343         LyXVC const & lyxvc() const;
344
345         /// Where to put temporary files.
346         std::string const & temppath() const;
347
348         /// Used when typesetting to place errorboxes.
349         TexRow & texrow();
350         TexRow const & texrow() const;
351
352         ///
353         ParIterator par_iterator_begin();
354         ///
355         ParConstIterator par_iterator_begin() const;
356         ///
357         ParIterator par_iterator_end();
358         ///
359         ParConstIterator par_iterator_end() const;
360
361         /** \returns true only when the file is fully loaded.
362          *  Used to prevent the premature generation of previews
363          *  and by the citation inset.
364          */
365         bool fully_loaded() const;
366         /// Set by buffer_funcs' newFile.
367         void fully_loaded(bool);
368
369         /// Our main text (inside the top InsetText)
370         Text & text() const;
371
372         /// Our top InsetText!
373         Inset & inset() const;
374
375         //
376         // Macro handling
377         //
378         ///
379         void buildMacros();
380         ///
381         bool hasMacro(docstring const & name) const;
382         ///
383         MacroData const & getMacro(docstring const & name) const;
384         ///
385         void insertMacro(docstring const & name, MacroData const & data);
386
387         ///
388         void saveCursor(StableDocIterator cursor, StableDocIterator anchor);
389         ///
390         StableDocIterator getCursor() const { return cursor_; }
391         ///
392         StableDocIterator getAnchor() const { return anchor_; }
393         ///
394         void changeRefsIfUnique(docstring const & from, docstring const & to,
395                 Inset::Code code);
396 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
397 /// including preamble
398         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end, bool full_source);
399
400         /// errorLists_ accessors.
401         //@{
402         ErrorList const & errorList(std::string const & type) const;
403         ErrorList & errorList(std::string const & type);
404         //@}
405
406         //@{
407         TocBackend & tocBackend();
408         TocBackend const & tocBackend() const;
409         //@}
410
411 private:
412         /** Inserts a file into a document
413             \return \c false if method fails.
414         */
415         ReadStatus readFile(Lexer &, support::FileName const & filename,
416                             bool fromString = false);
417
418         /// Use the Pimpl idiom to hide the internals.
419         class Impl;
420         /// The pointer never changes although *pimpl_'s contents may.
421         boost::scoped_ptr<Impl> const pimpl_;
422
423         /// Save the cursor Position on Buffer switch
424         /// this would not be needed if every Buffer would have
425         /// it's BufferView, this should be FIXED in future.
426         StableDocIterator cursor_;
427         StableDocIterator anchor_;
428         /// A cache for the bibfiles (including bibfiles of loaded child
429         /// documents), needed for appropriate update of natbib labels.
430         mutable std::vector<support::FileName> bibfilesCache_;
431 };
432
433
434 } // namespace lyx
435
436 #endif