How can I make Atom fold code automatically?


#1

When I open large Python files in Atom, I usually use Atom’s code-folding feature immediately so that I can see the class and function headers easily, without every line of code. Does anyone know how I can make Atom do this automatically when I open a certain type of file?


#2

You could put something in your Init Script that takes a particular action when new editors are opened. Perhaps something along these lines (note: not tested):

atom.workspaceView.eachEditorView (view) ->
  editor = view.getEditor?()
  editor.foldAll() if editor?.getGrammar().name is 'Python'

#3

Thanks, that works great!


#4

New Atom user here!

Tried bending this into what I needed until I came across another post informing me that the structure had changed a bit. Here is what I ended up with:

# folds Python code, at base level only, when a new window is opened
foldCode = (editor) ->
  editor.foldAllAtIndentLevel(0)

atom.workspace.observeTextEditors (editor) ->
  if editor.getGrammar().name is 'Python'
    foldCode(editor)

I am completely new to Atom and CoffeeScript for that matter as well. Please let me know if there is any missteps here!

Thanks!


#5

I guess the DSL has changed since this thread was active last.

I could use a functionality that automatically code-folds Ruby test file contents whenever I open such a file.

The file contents follow this structure:

RSpec.describe CreativeSubscriptions::StatisticsConcerns::Common, type: :model do 
  describe ".paymode_checkable_types" do    
  end

  describe ".paymode_ensureable_types" do       
  end
end

Namely that there is a main do block for the class in question and a sub-do block for each method being tested.

The expected behavior of needed functionality is to block-fold files with filenames ending with “_spec.rb” up to the main do block leaving

RSpec.describe CreativeSubscriptions::StatisticsConcerns::Common, type: :model do 
  describe ".paymode_checkable_types" do ...    

  describe ".paymode_ensureable_types" do  ...     
 
end

I suspect @twoodrow’s editor.foldAllAtIndentLevel(0) plays a role (argument of 1 perhaps in my case?), but I am at a loss about how to trigger the folding on files I want at opening.


#6

My solution was:

# Usually namespace at 0, class at 1, methods at 2
foldCode = (editor) ->
  editor.foldAllAtIndentLevel(2)

atom.workspace.onDidAddTextEditor (e) ->
  if e.textEditor.getGrammar().name is 'TypeScript'
    foldCode(e.textEditor)