Tuesday, April 12, 2011

Code folding in Emacs

Code folding is a feature to wrap or unwrap a block of code. It can help you to see an overview of your code. This is a quick and simple way to have that feature in Emacs. I modified it a little bit to make it more flexible as the way I want.

;; code folding
(defun toggle-selective-display (level)
  (interactive "nEnter indentation level: ")
  (set-selective-display level)
  )

(global-set-key "\M-3" 'toggle-selective-display)
So, if I have this code:

class User < ActiveRecord
  has_many :projects
  has_many :assignments

  def full_name
    "#{first_name} #{last_name}"
  end

  def show_project_names
    projects.each do |prj|
      puts prj.name
    end
  end
  
end
then when I press Alt+3 4, all code that was indented at level 4 (4 spaces) will be wrapped as below:

class User < ActiveRecord
  has_many :projects
  has_many :assignments

  def full_name...
  end

  def show_project_names...
  end
  
end
if I press Alt+3 2, all code indented at level 2 will be wrapped:

class User < ActiveRecord...  
end
if I press Alt+3 0, wrapped code will be unwrapped again.

class User < ActiveRecord
  has_many :projects
  has_many :assignments

  def full_name
    "#{first_name} #{last_name}"
  end

  def show_project_names
    projects.each do |prj|
      puts prj.name
    end
  end
  
end
It's quite fun, right?

No comments: