On Tue, Jan 10, 2017 at 9:47 AM, Matt Price <moptop99@gmail.com> wrote:

In a buffer with text before the first heading, I get an error using org-map-entries in this function:

(defun org-export-all (backend)
  "Export all subtrees that are *not* tagged with :noexport: to
separate files.

Note that subtrees must have the :EXPORT_FILE_NAME: property set
to a unique value for this to work properly."
  (interactive "sEnter backend: ")
  (let ((fn (cond ((equal backend "html") 'org-html-export-to-html)
                  ((equal backend "latex") 'org-latex-export-to-latex)
                  ((equal backend "pdf") 'org-latex-export-to-pdf))))
    (save-excursion
      (set-mark (point-min))
      (goto-char (point-max))
      (org-map-entries (lambda () (funcall fn nil t)) "-noexport" 'region-start-level))))

The error is :
Debugger entered--Lisp error: (error "Before first headline at position 1 in buffer test.org<2>")

Is there a better way to map over first-level heading, 
or alternatively, a better way to set the mark? I tried setting mark to :


(goto-char (point-min)) (re-search-forward "
\\\*"))

but that gave strange results, with the wrong trees 
being sent to individual files.

I think I misrepresented the problem in my initial email. 

With a test file test-export.org:

-----------
Pre-heading text

* Heading 1
:PROPERTIES:
:EXPORT_FILE_NAME: 01-heading-1
:END:
text of heading 1

* Heading 2
:PROPERTIES:
:EXPORT_FILE_NAME: 02-heading-2
:END:

text of heading 2
-----------

running eval-expression

(org-map-entries (lambda () (funcall 'org-org-export-to-org nil t)) "-noexport" nil)

gives the expected result (2 line breaks added for ease of reading):

-------------------------
$ cat 01-heading-1.org 02-heading-2.org

# Created 2017-01-10 Tue 12:51
#+TITLE: Heading 1
#+AUTHOR: Matt Price
text of heading 1

# Created 2017-01-10 Tue 12:51
#+TITLE: Heading 2
#+AUTHOR: Matt Price
text of heading 2
-------------------------------

However, running

#+BEGIN_SRC emacs-lisp
(set-mark (point-min))
    (goto-char (point-max))
    (org-map-entries (lambda () (funcall 'org-org-export-to-org nil t)) "-noexport" 'region-start-level)
#+END_SRC

gives the error:

Debugger entered--Lisp error: (error "Before first headline at position 1 in buffer export.org<2>")


If I delete the text before the first heading, the command runs without error but produces the following output:

--------
$ cat 01-heading-1.org 02-heading-2.org

# Created 2017-01-10 Tue 12:57
#+TITLE: Heading 1
#+AUTHOR: Matt Price
text of heading 1

# Created 2017-01-10 Tue 12:57
#+TITLE: Heading 1
#+AUTHOR: Matt Price
* Heading 1
text of heading 1
-------------

If I make additional headings, en every case the content of the resultant files will be replaced by the contents of the first file. 

What's going on here? Can anyone else reproduce this? I'm seeing it on org 9.0.3 up to date as of today, emacs git from 2017-01-04.