使用Org-Babel控制缩进

7
当使用Org–Babel编写Python文档时,我需要能够控制缩进级别(可以通过:indentation-level 3 显式控制,也可以通过一些巧妙的指示隐式控制)。
这是一个演示问题的示例文件。
#+BEGIN_SRC python :tangle "sample.py"
  class Test:
      def __init__(self):
          self.a = 'a test class'
#+END_SRC
#+BEGIN_SRC python :tangle "sample.py"
      def say_hi(self):
          print 'Hi from this Test object!'
          print 'ID: {}'.format(repr(self))
          print 'Data: {}'.format(str(self.__dict__))
#+END_SRC

@Tobias 当我使用 org-babel-tangle 命令编织文件时,如果在 #+begin_src 环境中添加空格前缀,则不会保留缩进格式。如果将所有代码都放在一个代码块中,则不会出现这个问题,但是为了清晰易懂,最好将其分成几个部分进行解释和说明。 - Sean Allred
但是,这对我有效!所有缩进都是从org文件中逐字复制的。 - Tobias
@Tobias 多奇怪啊...我会上传一个视频来证明我不是疯了XD - Sean Allred
@Tobias Org 版本 8.2.4:http://www.youtube.com/watch?v=T0gGW3T4zRo(警告:我的键盘声有点大) - Sean Allred
@Tobias 我刚刚为新机器更新了emacs,所以我会重新测试你的答案。同时,作为期间我所做的记录,使用noweb引用实际上解决了这个问题。 - Sean Allred
显示剩余2条评论
3个回答

9

org-src-preserve-indentation设置为t


看起来,即使使用了这个设置,第一行仍然缩进得很差:http://i.stack.imgur.com/0EwwH.png - Sean Allred
1
这确实可以运行,但一个令人讨厌的副作用是所有代码块(不仅仅是Python)都变成了左对齐。有没有办法避免这种情况,或者至少将此选项限制在Python源代码块中?谢谢。 - Ajned

4

我不是很喜欢Tobias的回答,因为当我使用org-edit-special (C-c ')编辑代码块时,我的python-mode缓冲区会提示错误(我有几个带语法检查器的python次要模式),因为独立方法块的意外缩进(因为使用org-src-preserve-indentation设置后,我将在每个方法的单独块前面有缩进)。所以,我更喜欢使用org-mode的:noweb头部参数来解决这个问题:

#+BEGIN_SRC python :tangle "sample.py" :noweb yes
  class Test:
      <<init_method>> # these are indented
      <<more_methods>> # these are indented
#+END_SRC

#+BEGIN_SRC python :noweb-ref init_method
  def __init__(self):
      self.a = 'a test class'
#+END_SRC

#+BEGIN_SRC python :noweb-ref more_methods
  def say_hi(self):
      print 'Hi from this Test object!'
      print 'ID: {}'.format(repr(self))
      print 'Data: {}'.format(str(self.__dict__))
#+END_SRC

只需在类定义中缩进Noweb语法引用(双<< >>),其他块("init_method"和"more_methods")将根据您的缩进进行解析。因此,最终输出的"sample.py"文件看起来像这样:
class Test:
    def __init__(self):
        self.a = 'a test class'
    def say_hi(self):
        print 'Hi from this Test object!'
        print 'ID: {}'.format(repr(self))
        print 'Data: {}'.format(str(self.__dict__))

很好!

1

我知道这不是理想的解决方案,但作为一种解决方法,您可以在源代码块中插入一个注释(特定于您的编程语言),并在该注释之后进行所需的缩进。这样做也会在退出编辑缓冲区时保留缩进。

#+BEGIN_SRC python :tangle "sample.py"
  class Test:
      def __init__(self):
          self.a = 'a test class'
#+END_SRC
#+BEGIN_SRC python :tangle "sample.py"
  # This is my dummy python comment to keep the correct indentation 
      def say_hi(self):
          print 'Hi from this Test object!'
          print 'ID: {}'.format(repr(self))
          print 'Data: {}'.format(str(self.__dict__))
#+END_SRC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接