【问题标题】:Control indentation with Org–Babel使用 Org–Babel 控制缩进
【发布时间】:2014-01-03 00:54:48
【问题描述】:

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

【问题讨论】:

  • 嗯,org-babel 尊重编程模式的缩进。如果您使用C-' 编辑代码sn-p,您可以使用C-c >python-mode 更改缩进。但是,我想这不是你想要的。想要选择:indentation-level的原因是什么?
  • @Tobias 当我org-babel-tangle 文件时,在#+begin_src 环境中使用空白前缀时不遵守缩进。如果我将所有内容都保存在一个源代码块中,一切都很好,但是明智的做法是将其拆分并解释每个部分。
  • 但是,这对我有用!所有缩进都是从 org 文件中逐字复制的。
  • @Tobias 好奇怪……我会上传视频来证明我没有疯XD
  • @Tobias Org 8.2.4 版:youtube.com/watch?v=T0gGW3T4zRo(警告:我的键盘有点响)

标签: python emacs org-mode literate-programming org-babel


【解决方案1】:

org-src-preserve-indentation 设置为t

【讨论】:

  • 看来,即使有这一套,第一行的缩进还是很差:i.stack.imgur.com/0EwwH.png
  • 嗯,这确实有效,但一个恼人的副作用是所有代码块(不仅是 python)都变得左对齐。有没有办法避免这种情况,或者至少将此选项仅限于 python 源块?谢谢。
【解决方案2】:

我并不完全喜欢Tobias' answer,因为当我org-edit-special (C-c ') 一个代码块时,我的python 模式缓冲区会对我大喊大叫(我有几个带有语法检查器的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 语法引用(双 &lt;&lt; &gt;&gt;),其他块(“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__))

不错!

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多