Next: , Previous: , Up: Curses Tutorial   [Contents][Index]


4.8 Attributes

Attributes can be used to print characters with some special effects. Attributes, when set prudently, can present information in an easy, understandable manner.

The following program takes a scheme file as input and prints the file with comments in bold. It does so by turning on the A_BOLD attribute using attr-on! when a semicolon is detected, and then turning of the A_BOLD attribute using attr-off! when a newline is detected. Have a look.

#!/usr/bin/guile
!#

(use-modules (ncurses curses)
             (ice-9 format))

;; A helper function that return the cursor's current row
(define (getrow win)
  (car (getyx win)))

;; The program should be passed a filename from the command line
(if (not (eqv? 2 (length (command-line))))
    (begin
      (format #t "Usage: ~a <scm file name>~%" (car (command-line)))
      (primitive-exit 1)))

(let* ((filename (cadr (command-line)))
       (fport (open-input-file filename))
       (stdscr (initscr)))

  ;; Read one char at a time from the file
  (let loop ((ch (read-char fport)))
    (if (not (eof-object? ch))
	(begin
	  ;; Wait for a key press once a page
	  ;; of text has been printed
	  (if (eqv? (getrow stdscr) (- (lines) 1))
	      (begin
		(addstr stdscr "<-Press any key->")
		(refresh stdscr)
		(getch stdscr)
		(clear stdscr)
		(move stdscr 0 0)))
	  ;; Bold all text between a semicolon
	  ;; and the end of a line
	  (cond
	   ((eqv? ch #\;)
	    (attr-on! stdscr A_BOLD))
	   ((eqv? ch #\nl)
	    (attr-off! stdscr A_BOLD)))
	  (addch stdscr (normal ch))
	  (refresh stdscr)
	  (loop (read-char fport)))

	;; Clean up and exit
	(begin
	  (addstr stdscr "<-Press any key->")
	  (refresh stdscr)
	  (getch stdscr)
	  (endwin)
	  (close-input-port fport)))))

One important thing to note is that in this program, addch is always passed a normal, un-bolded, character. Note the line

          (addch stdscr (normal ch))

But yet, the character printed by addch may still appear as bold on the screen. This is because the character attributes passed to addch combine with the character attributes set by attr-on!. If attr-on! has set the window’s default attributes to bold, that will merge with the attributes passed to addch.

The function also introduces the useful function getyx. It returns the coordinates of the present cursor as a list of two elements.

The above program is really a simple one which doesn’t do much. Along these lines once could write a more useful program which reads a scheme file, parses it, and prints it in different colors.


Next: , Previous: , Up: Curses Tutorial   [Contents][Index]