+
+#ifndef NO_PAGER
+/* reset pager state */
+void
+rdline_asyncpager_reset(struct rdline *rdl)
+{
+ if (rdl->pager_buf) {
+ free(rdl->pager_buf);
+ rdl->pager_buf = NULL;
+ }
+ rdl->pager_lines = 0;
+ rdl->pager_len = 0;
+ rdl->pager_off = 0;
+}
+
+/* Return the offset of the i-th occurence of char c in string s. If
+ * there is less than i occurences, return -1 and fill i with the
+ * count. */
+static int
+strnchr(const char *s, char c, int *i)
+{
+ int n = 0;
+ const char *orig = s;
+
+ while (*s) {
+ if (*s == c)
+ n++;
+ if (*i == n)
+ return s - orig;
+ s++;
+ }
+ *i = n;
+ return -1;
+}
+
+/* display a page of data from pager, return 0 if all is displayed */
+static int
+rdline_pager_next_page(struct rdline *rdl)
+{
+ int lines = RDLINE_MAX_LINES;
+ int displen;
+ char *s;
+
+ s = rdl->pager_buf;
+ if (s == NULL)
+ return 0;
+
+ rdline_printf(rdl, vt100_home);
+ rdline_printf(rdl, vt100_clear_right);
+
+ s += rdl->pager_off;
+
+ /* we know that s is 0-terminated */
+ displen = strnchr(s, '\n', &lines);
+ rdl->pager_lines = lines;
+
+ /* we can display all the data */
+ if (displen == -1) {
+ write(rdl->fd_out, s, rdl->pager_len);
+ free(rdl->pager_buf);
+ rdl->pager_buf = NULL;
+ return 0;
+ }
+
+ displen = displen + 1; /* include \n */
+ write(rdl->fd_out, s, displen);
+ rdl->pager_off += displen;
+ rdl->pager_len -= displen;
+
+ rdline_printf(rdl, "--- press a key to continue ---");
+ return -1;
+}
+
+/* push data in pager */
+static int
+rdline_pager_push(struct rdline *rdl, char *s, int len)
+{
+ /* display as many lines as we can */
+ if (rdl->pager_lines < RDLINE_MAX_LINES) {
+ int lines = RDLINE_MAX_LINES - rdl->pager_lines;
+ int displen;
+
+ /* we know that s is 0-terminated */
+ displen = strnchr(s, '\n', &lines);
+ rdl->pager_lines += lines;
+
+ /* we can display all the data */
+ if (displen == -1) {
+ write(rdl->fd_out, s, len);
+ return 0;
+ }
+ displen = displen + 1; /* include \n */
+ write(rdl->fd_out, s, displen);
+ s += displen;
+ len -= displen;
+ }
+
+ if (rdl->pager_buf == NULL) {
+ rdline_printf(rdl, "--- press a key to continue ---");
+ }
+ rdl->pager_buf = realloc(rdl->pager_buf, rdl->pager_len + len);
+ if (rdl->pager_buf == NULL) {
+ rdline_asyncpager_reset(rdl);
+ return -1;
+ }
+
+ memcpy(rdl->pager_buf + rdl->pager_len, s, len);
+ rdl->pager_len += len;
+ return 0;
+}
+
+/* XXX we should have a specific return value when displaying will be
+ * asynchronous, we may also have a callback */
+int
+rdline_asyncpager_printf(struct rdline *rdl, const char *fmt, ...)
+{
+ int n;
+ char *buf;
+ va_list ap;
+
+ if (rdl->fd_out < 0)
+ return -1;
+
+ buf = malloc(BUFSIZ);
+ if (buf == NULL)
+ return -1;
+
+ va_start(ap, fmt);
+ n = vsnprintf(buf, BUFSIZ, fmt, ap);
+ va_end(ap);
+
+ if (n >= BUFSIZ)
+ n = BUFSIZ-1;
+ if (n > 0)
+ rdline_pager_push(rdl, buf, n);
+ free(buf);
+ return n;
+}
+#endif /* !NO_PAGER */