6

使用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
4

3 回答 3

9

设置org-src-preserve-indentationt

于 2014-01-03T11:50:12.540 回答
3

我并不完全喜欢Tobias 的回答,因为当我org-edit-special( C-c ') 一个代码块时,我的 python 模式缓冲区会对我大喊大叫(我有几个带有语法检查器的 python 次要模式),因为带有独立方法的块的意外缩进(因为使用org-src-preserve-indentationset,我会在我的所有方法前面在它们的各个块中缩进)。因此,我喜欢使用 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__))

好的!

于 2018-03-31T15:14:46.683 回答
0

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

#+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
于 2016-06-28T14:55:56.210 回答